在我的文本文件中,我有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
答案 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:
表示该行是否为空。