Home > database >  How can I parse a txt file and create dictionary from a specific part of the txt file using Python?
How can I parse a txt file and create dictionary from a specific part of the txt file using Python?

Time:01-17

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
} 

the txt file contains: enter image description here

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:
        ....

CodePudding user response:

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'}

  •  Tags:  
  • Related