【问题标题】:Counting words occurances in a string using Dictionaries使用字典计算字符串中的单词出现次数
【发布时间】:2015-05-21 10:12:34
【问题描述】:

我正在尝试计算字符串中每个单词的出现次数。然后我想将结果作为字典返回,将单词作为键,将它们的出现次数作为值。 但是,当我运行我的代码时,它会返回以下语句: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  

【问题讨论】:

    标签: loops python-3.x dictionary


    【解决方案1】:

    首先我认为你的意思是:

    dictionary[word]+=1
    

    而不是input_str[word] += 1,但这不是此任务的方式。它还会引发KeyError 异常。

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

    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})
    

    【讨论】:

    • 谢谢!。但我将.count() 函数用作lower_sentence.count(word)。它工作得很好。
    • @Moh'dH 欢迎,是的,您可以使用count 方法,但Counter 对于长字符串更有效!
    猜你喜欢
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 2015-09-14
    • 2022-01-06
    • 2021-01-09
    • 2021-12-27
    • 2014-06-11
    • 2013-02-01
    相关资源
    最近更新 更多