I have a text file that detects the amount of monitors that are active. I want to extract specific data from each line and include it in a list.
The text file looks like this:
[EnumerateDevices]: Enumerating Devices.
DISPLAY\LGD03D7\4&ACE0355&1&UID68092928 : Generic PnP Monitor
DISPLAY\ABCF206\4&ACE0355&1&UID51249920 : Generic PnP Monitor
//
// here can be more monitors...
//
2 matching device(s) found.
I need to get the number after the UID in the middle of the text : 68092929 , 51249920 ..
I thought of doing the next:
a. enter each line in text
b. see if "UID" string exist
c. if it exists : split (here I dot know how to do it.. split by (" ") or ("&")
Is there any good idea you can advise? I don't understand how can I get the numbers after the UID (if the next number is longer than the previous ones for example) how can I get a command that does : ("If you see UID string, get all the data until you see first blank")
any idea? Thanks
Use regular expressions:
I would use a regular expresssion to extract the UID
e.g.
You can use the
split()
method.The output of the above snippet is a list containing:
['hello', 'this', 'is', 'a', 'test']
In your case, you can split on the substring "UID" and grab the second element in the list to get the number that you're looking for.
See docs here: https://docs.python.org/2/library/string.html#string.split
This is a bit esoteric but does the trick with some list comprehension:
the output is the list you are looking for I presume: ['68092928', '51249920']
Explanations:
if you read the whole file at once, otherwise if line by line just change the first line to line.split()
the split will have already stripped "junk" do each elem that contains the 'UID' string will be all set to int() or just print as a string