【问题标题】:How can I parse a txt file and create dictionary from a specific part of the txt file using Python?如何解析 txt 文件并使用 Python 从 txt 文件的特定部分创建字典?
【发布时间】:2022-01-14 17:17:53
【问题描述】:

我有一个 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:
        ....

【问题讨论】:

  • 能否请您添加文本而不是图像,这样会有所帮助。
  • @KnowledgeGainer 我刚刚添加

标签: python dictionary parsing


【解决方案1】:

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多