Reputation: 53
I have a txt file and I want to parse it using Python and then create a dictionary which contains as keys all the words in column a and as values the metrics in column b. I would like something like that:
{
"Cq":7.34s
"Pr":8.69s
"G(AM)":0.00s
}
text:
INFO : Query
INFO : ----------------------------------------------------------------------------------------------
INFO : a b
INFO : ----------------------------------------------------------------------------------------------
INFO : Cq 7.43s
INFO : Pr 8.69s
INFO : G(AM) 0.00s
INFO : ----------------------------------------------------------------------------------------------
I have done something like:
with open('k.txt') as f:
lines = f.readlines()
for line in lines:
....
Upvotes: 0
Views: 57
Reputation: 11090
You can do it somthing like this:
text = """INFO : Query
INFO : ----------------------------------------------------------------------------------------------
INFO : a b
INFO : ----------------------------------------------------------------------------------------------
INFO : Cq 7.43s
INFO : Pr 8.69s
INFO : G(AM) 0.00s
INFO : ----------------------------------------------------------------------------------------------"""
parts = text.split("INFO : ----------------------------------------------------------------------------------------------")
content = parts[2]
lines = content.split("\n")
import re
result = {}
for line in lines[1:4]:
parts = re.split(r"\s+",line[8:])
result[parts[0]]=parts[1]
print(result)
prints: {'Cq': '7.43s', 'Pr': '8.69s', 'G(AM)': '0.00s'}
Upvotes: 1