2016-02-19 153 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 
相关问题