簡體   English   中英

如何使用 Python 解析 txt 文件並從 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'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM