首页 > 解决方案 > 文本文件到字典,然后在 python 中打印信息

问题描述

嘿,每个人都对文本文件和将其放入字典有疑问。

所以我的代码首先从网站收集数据并将其写入文本文件。从那里我重新打开文件并将其放入字典以将数据从文本传输到字典。在while循环中,我得到了错误

 key,value = line.split()
ValueError: too many values to unpack (expected 2)

我不知道为什么如果我使用错误的方法将文本文件数据写入“countryName”程序中的新位置

def main():
    import requests
    webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
    data = requests.get(webFile) #connects to the file and gest a response object
    with open("capital.txt",'wb') as f:
        f.write(data.content) #write the data out to a file – wb used since thecontent from the response object is returned as abinary object.
    f.close()
    infile = open('capital.txt', 'r')
    line = infile.readline()
    countryName = {}
    while line != "":
        key,value = line.split() 
        countryName[key] = value
        line = infile.readline()
    infile.close()
    userInput = input("Enter a country name: ")
    for i in countryName:
        while(userInput != 'stop'):
            print("The per capita income in",countryName[key], "is",countryName[value])
            userInput = input("Enter a country name: ")
main()
    while line != "":
        key,value = line.split() 
        countryName[key] = value
        line = infile.readline()
    infile.close()

这就是我的问题出现的地方。

我正在尝试将文本文件信息放入字典中。完成后,我想遍历字典,并让用户输入国家名称。然后作为响应,程序找到国家名称并返回国家名称和资本收入。

因此,如果输入“美国”,输出将是“美国的人均收入为 54000 美元”,以此为例说明我在做什么。

键是国家名称,值是收入。

countryName = {} with open('capital.txt','r') as infile: for line in infile: num,key,value = line.split() countryName[key] = value num,key,value = infile.readline().split() #print(line) print(countryName)

标签: pythondictionary

解决方案


问题是每行返回三个值:行号、国家和人均收入:

fh.readline().split()
['2', 'Qatar', '$124,500']

为了解决这个问题,您可以在一次性变量中捕获第三个值:

n, key, val = fh.readline().split()

但是,有一个不同的问题,如果您的国家名称中有空格怎么办?

['190', 'Micronesia,', 'Federated', 'States', 'of', '$3,400']

您可以使用*arg语法来捕获变量中的任意数量的参数:

myline = ['190', 'Micronesia,', 'Federated', 'States', 'of', '$3,400']

num, *key, value = myline

# key is now ['Micronesia,', 'Federated', 'States', 'of']

然后您可以使用join创建单个字符串

key = ' '.join(key)
# 'Micronesia, Federated States of'

此外,保持程序中的约定一致也很重要。您使用with上下文处理程序打开和关闭较早的文件,这是一个很好的做法,因此也将其与其他文件一起保存。此外,您可以像这样直接遍历文件句柄:

with open('capital.txt', 'r') as infile:
    for line in infile: # no need to check the line contents or call readline
        num, *key, value = line.split()
        key = ' '.join(key)

# No need to close your file at the end either

最后,您的打印语句将引发KeyError

print("The per capita income in",countryName[key], "is",countryName[value])

您已经存储valuecountryName[key],因此查找仅针对key,而不是value

# key is already a string representing the country name
# countrName[key] is the value associated with that key
print("The per capita income in", key , "is", countryName[key])

推荐阅读