简体   繁体   English

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

[英]Reading a file and storing contents into a dictionary - Python

I'm trying to store contents of a file into a dictionary and I want to return a value when I call its key. 我试图将文件的内容存储到字典中,并且想在调用其键时返回一个值。 Each line of the file has two items (acronyms and corresponding phrases) that are separated by commas, and there are 585 lines. 文件的每一行都有两个项目(缩写和相应的短语),以逗号分隔,共有585行。 I want to store the acronyms on the left of the comma to the key, and the phrases on the right of the comma to the value. 我想在关键字的左侧存储首字母缩写词,在值的右侧存储短语。 Here's what I have: 这是我所拥有的:

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()

And here's what I get when I try to look up the values: 这是我尝试查找值时得到的结果:

>>> 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
>>> 

If I add return newDict to the end of the body of the function, it obviously just returns {'phrase[0]':'phrase[1]'} when I call read_file('acronyms.csv') . 如果将return newDict添加到函数主体的末尾,则当我调用read_file('acronyms.csv')时,它显然仅返回{'phrase[0]':'phrase[1]'} I've also tried {phrase[0]:phrase[1]} (no single quotation marks) but that returns the same error. 我也尝试过{phrase[0]:phrase[1]} (没有单引号),但是返回相同的错误。 Thanks for any help. 谢谢你的帮助。

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

Your original creates a new dictionary every iteration of the loop. 您的原始用户每次循环迭代都会创建一个新的字典。

First off, you are creating a new dictionary at every iteration of the loop. 首先,您将在循环的每次迭代中创建一个新的字典。 Instead, create one dictionary and add elements every time you go over a line. 而是创建一个字典并在每次浏览一行时添加元素。 Second, the 'phrase[0]' includes the apostrophes which turn make it a string instead of a reference to the phrase variable that you just created. 其次, 'phrase[0]'包含撇号,这些撇号将其变成字符串,而不是对您刚创建的词组变量的引用。

Also, try using the with keyword so that you don't have to explicitly close the file later. 另外,请尝试使用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