值错误:需要多于1个值才能解压缩

时间:2017-01-14 20:01:35

标签: python

我正在研究字数统计程序。

#!/usr/bin/env python
import sys

# maps words to their counts
word2count = {}

# input comes from STDIN
for line in sys.stdin:

    line = line.strip()


    word, count = line.split('\t', 1)

    try:
        count = int(count)
    except ValueError:
        continue

    try:
        word2count[word] = word2count[word]+count
    except:
        word2count[word] = count

for word in word2count.keys():
    print '%s\t%s'% ( word, word2count[word] )

此代码出错:

    word, count = line.split('\t', 1)
ValueError : need more than 1 value to unpack

1 个答案:

答案 0 :(得分:0)

word, count = line.split('\t', 1) - try中移动except应该有效:

for line in sys.stdin:
    line = line.strip()
    try:
        word, count = line.split('\t', 1)
        count = int(count)
    except ValueError:
        continue

这将跳过行的开头没有数字的所有行,这些行用来自行的其余部分的制表符分隔。