[通过从Python中读取文本文件创建带有固定键集的字典

问题描述 投票:0回答:2

输入:-包含3行的文本文件:

"Thank you
binhnguyen
2010-09-12
I want to say thank you to all of you."

输出:我想创建一个具有固定键的字典:'title','name','date','feedback'分别在上面的文件中存储4行。

{'title':'谢谢','name':'binhnguyen','date':'2010-09-12','feedback':'我想对大家说谢谢。'}

非常感谢

python dictionary readfile
2个回答
0
投票

给出file.txt所在的文件,格式是在问题中描述的格式,这将是代码:

path = r"./file.txt"

content = open(path, "r").read().replace("\"", "")
lines = content.split("\n")

dict_ = {
    'title': lines[0],
    'name': lines[1],
    'date': lines[2],
    'feedback': lines[3]
}
print(dict_)

0
投票

您基本上可以定义键列表并将其与行匹配。

示例:

key_list = ["title","name","date","feedback"]
text = [line.replace("\n","").replace("\"","")  for line in open("text.txt","r").readlines()]
dictionary = {}
for index in range(len(text)):
    dictionary[key_list[index]] = text[index]

print(dictionary)

输出:

{'title': 'Thank you', 'name': 'binhnguyen', 'date': '2010-09-12', 'feedback': 'I want to say thank you to all of you.'}
© www.soinside.com 2019 - 2024. All rights reserved.