1

所以我有一个这种格式的文件

CountryCode   CountryName
USA           United States

我要做的是以代码为键,以国家名称为值的字典。

我有一个旨在这样做的功能

def country(string):
    '''reads the contents of a file into a string and closes it.'''

    #open the file
    countryDict = {}
    fin = open(string, 'r')
    for eachline in fin:
        code, country = eachline.split()
        countryDict[code] = country

    print (countryDict)


    return countryDict

但是,当我尝试运行它时,我得到 ValueError: too many values to unpack (expected 2)。

这段代码不起作用的任何原因?我有一个类似的程序,它使用这样的代码创建用户名。

供参考的用户名程序代码,这行得通,为什么上面没有:

def main():
    print ("This program creates a file of usernames from a")
    print ("file of names.")

    # get the file names
    infileName = input("What file are the names in? ")
    outfileName = input("What file should the usernames go in? ")

    # open the files
    infile = open(infileName, 'r')
    outfile = open(outfileName, 'w')
    # process each line of the input file
    for line in infile:
        # get the first and last names from line
        first, last = line.split()
        # create a username
        uname = (first[0]+last[:7]).lower()
        # write it to the output file
        print(uname, file=outfile)


    # close both files

    infile.close()

    outfile.close()


    print("Usernames have been written to", outfileName)

if __name__ == '__main__':
    main()
4

2 回答 2

4

想想什么时候line

USA           United States

当你拆分它时,它会创建:

['USA', 'United', 'States']

当你去 do 时first, last = line.split(),它会尝试将三个值放入两个变量中(因此出现错误)。

为了防止这种情况,您可以拆分一次:

>>> first, last = 'USA           United States'.split(None, 1)
>>> first
'USA'
>>> last
'United States'
于 2013-07-17T06:35:07.020 回答
0

使用正则表达式的另一种方法

def country(string):
    fin = open(string, 'r')
    pat = r'\s*([A-Za-z0-9]*)\s+([A-Za-z0-9\s]*?)\n'
    tup = re.findall(pat, fin)
    return dict(tup)
于 2013-07-17T07:54:13.597 回答