[英]Create a dictionary with a fixed set of keys from reading text file in Python
Input: - A text file that contains 3 lines:输入: - 包含 3 行的文本文件:
"Thank you
binhnguyen
2010-09-12
I want to say thank you to all of you."
Output: I want to create a dictionary with fixed keys: 'title', 'name', 'date', 'feedback' that stores 4 lines in the file above respectively.输出:我想创建一个带有固定键的字典: 'title'、'name'、'date'、'feedback' ,分别在上面的文件中存储 4 行。
{'title': 'Thank you', 'name': 'binhnguyen', 'date': '2010-09-12 ', 'feedback': 'I want to say thank you to all of you.'}
{'title': 'Thank you', 'name': 'binhnguyen', 'date': '2010-09-12 ', 'feedback': '我想对你们所有人说声谢谢。'}
Thank you so much非常感谢
Given file.txt
where the file is and the format is the one described on the question this would be the code:给定
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_)
You can basically define a list of keys and match them with lines.您基本上可以定义一个键列表并将它们与行匹配。
Example:例子:
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)
Output:输出:
{'title': 'Thank you', 'name': 'binhnguyen', 'date': '2010-09-12', 'feedback': 'I want to say thank you to all of you.'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.