我正在研究字数统计程序。
#!/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
答案 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
这将跳过行的开头没有数字的所有行,这些行用来自行的其余部分的制表符分隔。