使用词典计算字符串中的单词出现次数

时间:2015-05-21 10:12:35

标签: loops python-3.x dictionary

我正在尝试计算字符串中每个单词的出现次数。然后我想将结果作为字典返回,将单词作为键及其出现次数作为值。 但是,当我运行我的代码时,它返回语句:line 8, in word_counter builtins.TypeError: string indices must be integers我不太明白这意味着什么。

def word_counter(input_str):
    lower_sentence = input_str.lower()
    dictionary = {}
    words = set(lower_sentence.split())
    for word in words:
        if word in input_str:
            input_str[word] += 1
        else:
            input_str[word] = 1
    return dictionary  

1 个答案:

答案 0 :(得分:3)

首先我认为你的意思是:

input_str[word] += 1

而不是KeyError,但它不是此任务的方式。它还会引发from collections import Counter print Counter('this is a sent this is not a word'.split()) Counter({'a': 2, 'this': 2, 'is': 2, 'word': 1, 'not': 1, 'sent': 1}) 例外。

您可以简单地使用collections.Counter作为此类任务的更多pythoinc方式。

department_id
相关问题