简体   繁体   English

在python中将文本文件读取到字典的问题

[英]Issue with reading a text file to a dictionary in python

Hey everyone just have an issue with a text file and putting it into a dictionary. 嘿,每个人都有一个关于文本文件的问题,并将其放入字典中。

So my code first starts off by gathering data from a website and writes it to a text file. 因此,我的代码首先从网站收集数据开始,然后将其写入文本文件。 From there I reopen the file and make it into a dictionary to transfer the data from the text to the dictionary. 从那里我重新打开文件,并将其放入字典,以将数据从文本传输到字典。 In the while loop, I am getting the error of 在while循环中,我得到了以下错误

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

Which I'm not sure why if I'm using the wrong method to write the text file data to the new place in the program of "countryName" 我不确定为什么我使用错误的方法将文本文件数据写入“ countryName”程序中的新位置的原因

Then once that compiles I want to be able to ask the user to input a country name and it will give the income capita of that country as shown in the print line. 然后,一旦编译完成,我希望能够要求用户输入国家/地区名称,它将给出该国家/地区的人均收入,如打印行所示。

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

each line also has a number in the beginning of it, and some country names have spaces in them, causing split to return longer lists. 每行的开头都有一个数字,并且某些国家/地区名称中包含空格,从而导致split返回更长的列表。 If you use regex to add in semicolons as delimiters, and trim leading and trailing whitespace, the splitting works properly. 如果使用正则表达式添加分号作为定界符,并修剪前导和尾随空白,则拆分工作正常。 This code would go inside the first while loop 该代码将进入第一个while循环

line = re.sub(r"(\$)", r";\1", line) # add semicolon before $ sign
line = re.sub(r'^([0-9]+)',r'\1;', line) # add semicolon after first group of numbers
num, key, value = re.split(r';', line) # split with semicolons as delimiters
countryName[key.strip()] = value.strip() # assign key and values after stripping whitespace

Split returns list, not dictionary. 拆分返回列表,而不是字典。

a = 'a b c'
list = a.split() #-> ['a','b','c']

Are you trying to do something like: 您是否正在尝试执行以下操作:

import requests

webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
data = requests.get(webFile).text #connects to the file and gest a response object
print(data)
while(1):
    name = input('Enter a country name: ')
    for a in data.splitlines():
        if name.lower() in a.lower():
            print(a.split()[-1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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