Pregunta

I run this code:

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)

And get this error:

word,score,std = string.split()
ValueError: need more than 1 value to unpack
¿Fue útil?

Solución

It's because string.lower().split() is returning a list with only one item. You cannot assign this to word,score,std unless this list has exactly 3 members; i.e. string contains exactly 2 spaces.


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

Otros consejos

This fails, since the string contains only one word:

string = "Fail"
word, score, std = string.split()

This works, because the number of words is the same as the number of variables:

string = "This one works"
word, score, std = string.split()
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)

I think this is what you are looking for, so correct me if I am wrong, but this basically checks if there are any spaces in which split() can split on, and acts accordingly.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top