Reputation: 1
Basically, I want to do following, I have a file full of such rows
Queue SIZE="1024" QID="8" TYPE="IOSQ" ADDRESS="0x218464000"
I need to do following,
If("IOSQ" in line):
then capture the value of Address which is "0x218464000"
How do I script this in Python?
Upvotes: 0
Views: 71
Reputation: 142146
One way is to use shlex.split
to standardise the data (quotes etc..), then build a dict of key=value, then take the address (or blank) if the type is "IOSQ" otherwise leave the address as blank, eg:
import shlex
s = 'Queue SIZE="1024" QID="8" TYPE="IOSQ" ADDRESS="0x218464000"'
d = dict(el.partition('=')[::2] for el in shlex.split(s))
# {'QID': '8', 'TYPE': 'IOSQ', 'ADDRESS': '0x218464000', 'SIZE': '1024', 'Queue': ''}
address = d.get('ADDRESS', '') if d.get('TYPE') == 'IOSQ' else ''
# '0x218464000'
This has the advantage that you're not relying on the ordering of key="something" in the text being the same and you can always access values for other keys if needs be later.
Upvotes: 0
Reputation: 13981
If the data are well-formatted, you might consider this:
lst = 'Queue SIZE="1024" QID="8" TYPE="IOSQ" ADDRESS="0x218464000"'.split()
def make_dict(lst):
return dict([tuple(item.split('=')) for item in lst])
dic = {}
dic[lst[0]] = make_dict(lst[1:])
print dic
Which gives:
{'Queue': {'QID': '"8"', 'ADDRESS': '"0x218464000"', 'TYPE': '"IOSQ"', 'SIZE': '"1024"'}}
Then you can access the value dic[lst[0]].get('ADDRESS', 'no address').strip('"')
.
Upvotes: 0
Reputation: 5696
You can use regular expressions.
import re
my_string = 'Queue SIZE="1024" QID="8" TYPE="IOSQ" ADDRESS="0x218464000"'
pattern = re.compile(r'IOSQ.*?ADDRESS="(\dx\d+)')
matches = re.findall(pattern, my_string)
print(matches)
The pattern is r'IOSQ.*?="(\dx\d+)
. r'something'
is a raw string, you should use this always. Then IOSQ
requires exact match of those letters. .*?
means match any character, from 0 to as few as possible (until a full match is found). Parenthesis makes findall
return only the contents of the parenthesis. \d
means digits 0 to 9. +
means one or more of the previous character being matched.
Upvotes: 2