[英]Convert Text File to Dictionary
假設我想在 Pycharm (keywords.txt) 中打開一個文本文件,假設這個文本文件包含一個單詞列表,帶有相應的數值,因此文本文件的格式如下:
apple, 3
banana, 5
happy, 7
tiger, 9
(數值范圍為 1-10)
我知道為了打開這個文件(以讀取模式),我們將執行以下操作:
with open('keywords.txt','r') as f:
我如何讀取文本文件每一行上的每個單詞,然后將其作為關鍵字存儲到字典中,然后還存儲其對應的數值?
例如:
dictionary = {'apple':'3','banana':'5','happy':'7','tiger':'9'}
我試過的:
with open('keywords.txt','r') as k:
size_to_read = 1
k_text = k.read(size_to_read)
while len(k_text) > 0:
if k_text.isalpha:
keywordic = dict.fromkeys({'k_text'})
print(keywordic)
k_text = k.read(size_to_read)
我真的不知道我要去哪里...
它只是打印一堆以下內容:
{'k_text': None}
def readFile(filename):
# Dict that will contain keys and values
dictionary = {}
with open(filename, "r") as f:
for line in f:
s = line.strip().split(", ")
dictionary[s[0]] = int(s[1])
return dictionary
這個作品通過打開文件,用刪除空白strip()
使用,分裂琴弦成列表strip()
然后設置鍵的字符串數組的第一部分s
,這是水果,並且該值到第二部分將其轉換為int
。
您可以使用for line in myfile:
逐行迭代文件。
dictionary = {}
with open("keywords.txt", "r") as file:
for line in file:
key, value = line.strip().split(",")
dictionary[key] = value
print(dictionary)
data_dict = { line.split(",")[0] : line.split(",")[1] for line in open('keywords.txt') }
只需逐行讀取文件,並且對於每一行字符串,使用`split(', ') 獲取該行中第一項和第二項的列表,然后您可以將這兩個字符串存儲在字典中,您可以如有必要,將第二個字符串轉換為整數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.