尝试在Python中添加到字典时发生ValueError
所以我有一个这种格式的文件尝试在Python中添加到字典时发生ValueError,python,list,file-io,dictionary,Python,List,File Io,Dictionary,所以我有一个这种格式的文件 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 =
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()
思考
行
何时为:
USA United States
拆分时,它将创建:
['USA', 'United', 'States']
当您执行first,last=line.split()
时,它将尝试将三个值放入两个变量中(因此产生错误)
要防止出现这种情况,可以拆分一次:
>>> first, last = 'USA United States'.split(None, 1)
>>> first
'USA'
>>> last
'United States'
思考
行
何时为:
USA United States
拆分时,它将创建:
['USA', 'United', 'States']
当您执行first,last=line.split()
时,它将尝试将三个值放入两个变量中(因此产生错误)
要防止出现这种情况,可以拆分一次:
>>> first, last = 'USA United States'.split(None, 1)
>>> first
'USA'
>>> last
'United States'
使用正则表达式的另一种方法
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)
使用正则表达式的另一种方法
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)
不是被骗(有点),而是巧合?不是被愚弄(有点),而是巧合吗?+1。此外,您不应该假设您的文件格式正确。相反,你应该编写代码来处理空行和只有一个单词的行等事情@JoelCornett我知道,但我学到的编程实践是添加基本功能(假设在游戏的这个阶段,用户会输入完美的输入)当程序的基本需求得到满足后,首先添加错误检查和其他提示。@user1768884:您应该(从一开始)将错误检查和日志记录功能结合起来。不过,优雅的错误处理功能可以在以后实现。+1。此外,您不应该假设您的文件格式正确。相反,你应该编写代码来处理空行和只有一个单词的行等事情@JoelCornett我知道,但我学到的编程实践是添加基本功能(假设在游戏的这个阶段,用户会输入完美的输入)当程序的基本需求得到满足后,首先添加错误检查和其他提示。@user1768884:您应该(从一开始)将错误检查和日志记录功能结合起来。不过,优雅的错误处理功能可以在以后实现。