如何解析 txt 文件并使用 Python 从 txt 文件的特定部分创建字典?

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

我有一个 txt 文件,我想使用 Python 解析它,然后创建一个字典,其中包含 a 列中的所有单词作为键,b 列中的度量作为值。我想要这样的东西:

{
"Cq":7.34s
"Pr":8.69s
"G(AM)":0.00s
} 

txt 文件包含:

正文:

INFO  : Query
INFO  : ----------------------------------------------------------------------------------------------
INFO  : a                              b 
INFO  : ----------------------------------------------------------------------------------------------
INFO  : Cq                           7.43s
INFO  : Pr                           8.69s
INFO  : G(AM)                        0.00s
INFO  : ----------------------------------------------------------------------------------------------

我做过类似的事情:

with open('k.txt') as f:
    lines = f.readlines()
    for line in lines:
        ....

你可以这样做:

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)

打印:{'Cq': '7.43s', 'Pr': '8.69s', 'G(AM)': '0.00s'}