Python ValueError:没有足够的值来解包(预期值为2,实际值为1)

2024-10-03 21:32:03 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的文本文件中,我有字符串数据,我试图使用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

Tags: 数据字符串linereplacefilehappyclear文本文件
2条回答

发生这种情况是因为文件末尾有超过1行空行。 代码的其余部分工作正常

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

if not clear_line:
    continue

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

如果文件中有任何空行,则可能会导致该错误,因为您告诉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:表示该行不是空的

相关问题 更多 >