2013-07-17 15 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)