Reputation: 161
I have a log file like this
………………
19:07:57.166 [INFO]keyword = 3 ...
19:08:13.664 [INFO]keyword = 2 ...
………………
19:14:27.062 [INFO]keyword = 3 ...
19:14:43.061 [INFO]keyword = 2 ...
…………………………
How can I get only one result like "19:07:57.166" or "19:14:43.061" by keyword "keyword = 2" in python?
Upvotes: 1
Views: 78
Reputation: 1065
regular expression
(i.e.: re
module is powerful to do a such task). Here I give you another way to achieve your goal:
# contains the logs data (e.g: it is an example)
lines = [
"19:07:57.166 [INFO]keyword = 3 ...",
"19:08:13.664 [INFO]keyword = 2 ...",
"19:14:27.062 [INFO]keyword = 3 ...",
"19:14:43.061 [INFO]keyword = 2 ...",
]
results = [] # contains all the results
for line in lines:
line_split = line.split("[INFO]")
if line_split[1][10] == '2':
results.append(line_split[0].strip())
print(results)
Outputs:
['19:08:13.664', '19:14:43.061']
Upvotes: 0
Reputation: 71461
A possibility is to use re
to transform your data into a list of dictionaries, making lookup with target keys a much cleaner process:
import re
data = [dict(zip(['val', 'keyword'], re.findall('^[\.\d:]+|(?<=keyword\s=\s)\d+', i))) for i in open('filename.txt')]
result = [i['val'] for i in data if int(i['keyword']) == 2]
Output:
['19:08:13.664', '19:14:43.061']
Upvotes: 1
Reputation: 2806
you can split each line by '19:07:57.166 [INFO]keyword = 3'.split('[INFO]')
or you can do it with regex
import re
line = '19:07:57.166 [INFO]keyword = 3'
result = re.match('(.*)\[INFO\](.*)', line)
result.group(1) # 19:07:57.166
result.group(2) # keyword = 3
import re
line = '19:07:57.166 [INFO]keyword = 2'
result = re.match('(.*)\[INFO\]keyword = 2', line)
result.group(1) # 19:07:57.166
Upvotes: 1