Python ValueError:没有足够的值可解包(预期2,得到1)

时间:2020-06-20 03:57:34

标签: python split iterable-unpacking

在我的文本文件中,我有Strings数据,我尝试使用Split()对其进行解压缩,但不幸的是给我的错误是“ ValueError:没有足够的值要解压(预期2,得到1)” 如果您知道,请帮助我解决问题

with open('Documents\\emotion.txt', 'r') as file:
    for line in file:
        clear_line = line.replace("\n", '').replace(",", '').replace("'", '').strip()
        print(clear_line)
        word,emotion = clear_line.split(':')

我有这种类型的数据

victimized: cheated
accused: cheated
acquitted: singled out
adorable: loved
adored: loved
affected: attracted
afflicted: sad
aghast: fearful
agog: attracted
agonized: sad
alarmed: fearful
amused: happy
angry: angry
anguished: sad
animated: happy
annoyed: angry
anxious: attracted
apathetic: bored

2 个答案:

答案 0 :(得分:1)

由于文件末尾超过1个空行而导致发生。 您其余的代码工作正常。

您可以执行以下操作以避免该错误。

if not clear_line:
    continue

word, emotion = clear_line.split(':')

答案 1 :(得分:0)

如果文件中有任何空行,可能会导致该错误,因为您告诉python将['']解压缩为word, emotion。要解决此问题,您可以像这样添加if语句:

with open('Documents\\emotion.txt', 'r') as file:
    for line in file:
        if line:
            clear_line = line.replace("\n", '').replace(",", '').replace("'", '').strip()
            print(clear_line)
            word,emotion = clear_line.split(':')

if line:表示该行是否为空。