我运行此代码:
def score(string, dic):
for string in dic:
word,score,std = string.lower().split()
dic[word]=float(score),float(std)
v = sum(dic[word] for word in string)
return float(v)/len(string)
并收到此错误:
word,score,std = string.split()
ValueError: need more than 1 value to unpack
答案 0 :(得分:4)
这是因为string.lower().split()
返回的列表只包含一个项目。除非此列表中只有3个成员,否则您无法将其分配给word,score,std
;即string
恰好包含2个空格。
a, b, c = "a b c".split() # works, 3-item list
a, b, c = "a b".split() # doesn't work, 2-item list
a, b, c = "a b c d".split() # doesn't work, 4-item list
答案 1 :(得分:0)
这失败了,因为字符串只包含一个单词:
string = "Fail"
word, score, std = string.split()
这是有效的,因为单词的数量与变量的数量相同:
string = "This one works"
word, score, std = string.split()
答案 2 :(得分:0)
def score(string, dic):
if " " in dic:
for string in dic:
word,score,std = string.lower().split()
dic[word]=float(score),float(std)
v = sum(dic[word] for word in string)
return float(v)/len(string)
else:
word=string.lower()
dic[word]=float(score),float(std)
v = sum(dic[word] for word in string)
return float(v)/len(string)
我认为这就是你要找的东西,所以如果我错了,请纠正我,但这基本上会检查split()
是否有任何可以拆分的空格,并采取相应的行动。