我正在做一个字数统计程序。在
#!/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] )
此代码的错误:
^{pr2}$
在
try
-except
中移动word, count = line.split('\t', 1)
应该可以:这将跳过所有在行首没有数字的行,该行的开头用制表符与行的其余部分隔开。在
相关问题 更多 >
编程相关推荐