0

我正在尝试修复此代码:

def word_counter (input_str):
    input_str1 = input_str.lower()
    word = 0
    input_str2 = dict(enumerate(input_str1.split(), start=1))
    if word in input_str2:
        input_str2[word] += 1
    else:
        input_str2[word] = 1
    return (input_str2)
word_count_dict = word_counter("This is a sentence")
print(sorted(word_count_dict.items()))

因此,而不是输出只是:

[(0, 1), (1, 'this'), (2, 'is'), (3, 'a'), (4, 'sentence')]

相反,它将返回 input_str 中每个单词的数量,如下所示:

[('a', 1), ('is', 1), ('sentence', 1), ('this', 1)]

任何帮助,将不胜感激

4

1 回答 1

2

您可以使用collections.Counter

>>> from collections import Counter
>>> c = Counter('This is a a a sentence'.split())
>>> c
Counter({'a': 3, 'This': 1, 'is': 1, 'sentence': 1})
>>> c['a']
3
>>> c['This']
1
>>> c.items()
[('This', 1), ('a', 3), ('is', 1), ('sentence', 1)]
于 2013-05-16T01:28:42.333 回答