繁体   English   中英

读取文件并将内容存储到字典中-Python

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM