【问题标题】:ValueError: not enough values to unpack (expected 2, got 1) when splitting lineValueError:拆分线时没有足够的值来解包(预期为 2,得到 1)
【发布时间】:2020-04-11 18:13:26
【问题描述】:
with open("words_10percent.txt") as f:
file_data = f.read()
word_frequency = {}
for line in file_data.split("\n"):
word, frequency = line.split(",")
word_frequency[word] = float(frequency)
在第 5 行中,尝试拆分行时出现值错误。
【问题讨论】:
标签:
python
debugging
error-handling
computer-science
【解决方案1】:
这段代码是绝对正确的。没有错误。再次检查您的文本文件。
出于演示目的,我在 'words_10percent.txt' 文件中添加了四行如下:
Ram, 50.55
class, 45.88
black, 35.99
data, 35.60
我得到以下输出:
Ram
50.55
class
45.88
black
35.99
data
35.60
【解决方案2】:
您的问题是由您的数据产生的,您至少在一行中没有字符 ,
你可以检查你的最后一行,可能有一个换行符\n
【解决方案3】:
你的错误是这一行:word, frequency = line.split(",")
有些行没有 " , "
试试这个:
with open("words_10percent.txt") as f:
file_data = f.read()
word_frequency = {}
for line in file_data.split("\n"):
if ',' not in line:
print('line without ,:', line)
continue
word, frequency = line.split(",")
word_frequency[word] = float(frequency)