debugging ValueError:拆分行时没有足够的值来解包(应为2,得到1)[重复]

nuypyhwy  于 2023-10-24  发布在  其他
关注(0)|答案(3)|浏览(110)

此问题已在此处有答案

Why do I get a ValueError when trying to split a line of input and assign to multiple variables?(4个答案)
2个月前关闭.

  1. with open("words_10percent.txt") as f:
  2. file_data = f.read()
  3. word_frequency = {}
  4. for line in file_data.split("\n"):
  5. word, frequency = line.split(",")
  6. word_frequency[word] = float(frequency)

在第5行中,我在尝试拆分该行时得到一个值错误。

gk7wooem

gk7wooem1#

你的错误是这一行:word,frequency = line.split(“,”) Some line doesn't have ”,“
试试这个:

  1. with open("words_10percent.txt") as f:
  2. file_data = f.read()
  3. word_frequency = {}
  4. for line in file_data.split("\n"):
  5. if ',' not in line:
  6. print('line without ,:', line)
  7. continue
  8. word, frequency = line.split(",")
  9. word_frequency[word] = float(frequency)
zpqajqem

zpqajqem2#

这段代码是完全正确的。没有错误。请再次检查您的文本文件。
为了演示的目的,我在'words_100.txt'文件中添加了四行,如下所示:

  1. Ram, 50.55
  2. class, 45.88
  3. black, 35.99
  4. data, 35.60

我得到以下输出:

  1. Ram
  2. 50.55
  3. class
  4. 45.88
  5. black
  6. 35.99
  7. data
  8. 35.60
展开查看全部
ct2axkht

ct2axkht3#

您的问题是由您的数据生成的,您至少有一行中没有字符,
你可以检查最后一行,可能有一个新的行字符\n

相关问题