2016-02-19 101 views
0

我試圖將文件的內容存儲到字典中,並且我想在調用其鍵時返回一個值。文件的每一行都有兩個用逗號分隔的項目(首字母縮略詞和相應的短語),並且有585行。我想將逗號左側的縮略詞存儲到鍵中,並將逗號右側的短語存儲爲值。下面是我有:讀取文件並將內容存儲到字典中 - Python

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]}(沒有單引號),但是返回相同的錯誤。謝謝你的幫助。

+1

我加入了蟒蛇標記你的問題,使得Python程序員就可以找到它。 – timgeb

回答

0
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 

您的原稿在循環的每次迭代中都會創建一個新詞典。

0

首先,您要在循環的每次迭代中創建一個新字典。相反,每次創建一個字典並添加元素時,您都需要添加元素。其次,'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 
1
def read_acronym_meanings(path:str): 
    with open(path) as f: 
     acronyms = dict(l.strip().split(',') for l in f) 
    return acronyms 
相關問題