2013-07-17 16 views
1

的时候所以我在这个格式ValueError异常试图添加到字典在Python

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异常的意图的功能:值过多解压(预期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() 
+0

http://stackoverflow.com/q/17653954/1971805不是欺骗(有点)但巧合多? – TerryA

回答

4

想想当line是:

USA   United States 

当你分割它,它会造成:

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

而当你去做first, last = line.split(),它会尝试把三个v将其变成两个变量(因此是错误)。

为了防止这种情况,你可以分割一次:使用

>>> first, last = 'USA   United States'.split(None, 1) 
>>> first 
'USA' 
>>> last 
'United States' 
+0

+1分裂一次 - 不错:) – alecxe

+1

+1。此外,你不应该认为你的文件格式正确。相反,你应该编写处理空白行和空白行等代码的代码,只需要一个单词等等。 –

+1

@JoelCornett我知道,但我学过的编程习惯是添加基本功能(假设在游戏的这个阶段用户将输入完美的输入),然后一旦满足程序的基本需求,就可以添加错误检查和其他花俏功能。 – user1768884

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)