值错误:unp需要1个以上的值

2024-09-28 23:43:10 发布

您现在位置: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] )

此代码的错误:

^{pr2}$

Tags: inimport程序envforbinusrcount
1条回答
网友
1楼 · 发布于 2024-09-28 23:43:10

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

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

这将跳过所有在行首没有数字的行,该行的开头用制表符与行的其余部分隔开。在

相关问题 更多 >