[英]Reading a file and storing contents into a dictionary - Python
我試圖將文件的內容存儲到字典中,並且想在調用其鍵時返回一個值。 文件的每一行都有兩個項目(縮寫和相應的短語),以逗號分隔,共有585行。 我想在關鍵字的左側存儲首字母縮寫詞,在值的右側存儲短語。 這是我所擁有的:
def read_file(filename):
infile = open(filename, 'r')
for line in infile:
line = line.strip() #remove newline character at end of each line
phrase = line.split(',')
newDict = {'phrase[0]':'phrase[1]'}
infile.close()
這是我嘗試查找值時得到的結果:
>>> read_file('acronyms.csv')
>>> acronyms=read_file('acronyms.csv')
>>> acronyms['ABT']
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
acronyms['ABT']
TypeError: 'NoneType' object is not subscriptable
>>>
如果將return newDict
添加到函數主體的末尾,則當我調用read_file('acronyms.csv')
時,它顯然僅返回{'phrase[0]':'phrase[1]'}
。 我也嘗試過{phrase[0]:phrase[1]}
(沒有單引號),但是返回相同的錯誤。 謝謝你的幫助。
def read_acronym_meanings(path:str):
with open(path) as f:
acronyms = dict(l.strip().split(',') for l in f)
return acronyms
def read_file(filename):
infile = open(filename, 'r')
newDict = {}
for line in infile:
line = line.strip() #remove newline character at end of each line
phrase = line.split(',', 1) # split max of one time
newDict.update( {phrase[0]:phrase[1]})
infile.close()
return newDict
您的原始用戶每次循環迭代都會創建一個新的字典。
首先,您將在循環的每次迭代中創建一個新的字典。 而是創建一個字典並在每次瀏覽一行時添加元素。 其次, 'phrase[0]'
包含撇號,這些撇號將其變成字符串,而不是對您剛創建的詞組變量的引用。
另外,請嘗試使用with關鍵字,這樣您以后就不必顯式關閉文件了。
def read(filename):
newDict = {}
with open(filename, 'r') as infile:
for line in infile:
line = line.strip() #remove newline character at end of each line
phrase = line.split(',')
newDict[phrase[0]] = phrase[1]}
return newDict
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.