首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python ValueError:没有足够的值来解包(预期为% 2,实际为% 1)

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

Stack Overflow用户
提问于 2020-06-20 11:57:34
回答 2查看 3.6K关注 0票数 0

在我的文本文件中,我有字符串数据,我试图使用Split()来解压它们,但不幸的是,我给出了错误"ValueError:没有足够的值来解压(预期为2,得到1)“,如果您知道,请帮助解决我

代码语言:javascript
复制
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(':')

我有这种类型的数据

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2020-06-20 12:05:55

由于文件的末尾有1个以上的空行,因此发生了。您的其余代码运行良好。

你可以在下面这样做来避免这个错误。

代码语言:javascript
复制
if not clear_line:
    continue

word, emotion = clear_line.split(':')
票数 1
EN

Stack Overflow用户

发布于 2020-06-20 12:21:37

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

代码语言:javascript
复制
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:表示该行是否为空。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62481464

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档