简体   繁体   English

读取文本文件并放入字典中

[英]read text file and put into dictionary

I am trying to figure out to read a file with multiple line and split the third line as keys and the fourth line as their value 我试图弄清楚读取多行的文件,并将第三行拆分为键,将第四行拆分为它们的值

file.txt file.txt

Ext: aaa bbb ccc ddd eee fff ggg hhh 
tcp: 000 111 222 333 444 555 666 777 
Ext: kkk lll mmm nnn ooo ppp qqq rrr 
tcp: 222 555 444 666 888 958 555 454

and desired output like this: 和所需的输出是这样的:

{
    "kkk" : "222",
    "lll" : "555",
    "mmm" : "444",
    "nnn" : "666",
    "ooo" : "888",
    "ppp" : "958",
    "qqq" : "555",
    "rrr" : "454"
}

you can try: 你可以试试:

with open('test.txt', 'r') as fp:
    lines = [e.strip() for e in fp.readlines()]
    my_dict = {l3 :l4 for l3, l4 in zip(lines[2].split()[1:], lines[3].split()[1:])}

print(my_dict)

output: 输出:

{'kkk': '222', 'lll': '555', 'mmm': '444', 'nnn': '666', 'ooo': '888', 'ppp': '958', 'qqq': '555', 'rrr': '454'}

Maybe there is a simpler solution, but that is what I would do 也许有一个更简单的解决方案,但这就是我会做的

file = open("path_to_your_file.txt", "r")
file.readline()
file.readline()
keys = file.readline().split()[1:]
values = file.readline().split()[1:]
d = dict(zip(keys, values))
file.close()
print(d)

And that is the output: 这就是输出:

{'ooo': '888', 'ppp': '958', 'nnn': '666', 'lll': '555', 'kkk': '222', 'rrr': '454', 'mmm': '444', 'qqq': '555'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM