簡體   English   中英

通過在 Python 中讀取文本文件創建具有一組固定鍵的字典

[英]Create a dictionary with a fixed set of keys from reading text file in Python

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

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

輸出:我想創建一個帶有固定鍵的字典: 'title'、'name'、'date'、'feedback' ,分別在上面的文件中存儲 4 行。

{'title': 'Thank you', 'name': 'binhnguyen', 'date': '2010-09-12 ', 'feedback': '我想對你們所有人說聲謝謝。'}

非常感謝

給定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_)

您基本上可以定義一個鍵列表並將它們與行匹配。

例子:

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

暫無
暫無

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

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