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()すると、3 つの値を 2 つの変数に入れようとします (したがって、エラーが発生します)。

これを防ぐために、一度分割できます。

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