Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 使用字典计算字符串中出现的单词数_Loops_Python 3.x_Dictionary - Fatal编程技术网

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

Loops 使用字典计算字符串中出现的单词数,loops,python-3.x,dictionary,Loops,Python 3.x,Dictionary,我试图计算字符串中每个单词出现的次数。然后,我想将结果作为字典返回,将单词作为键,将它们的出现次数作为值。 但是,当我运行代码时,它返回语句:第8行,在word\u计数器内置中。TypeError:字符串索引必须是整数我不太明白这是什么意思 def word_counter(input_str): lower_sentence = input_str.lower() dictionary = {} words = set(lower_sentence.split())

我试图计算字符串中每个单词出现的次数。然后,我想将结果作为字典返回,将单词作为键,将它们的出现次数作为值。 但是,当我运行代码时,它返回语句:
第8行,在word\u计数器内置中。TypeError:字符串索引必须是整数
我不太明白这是什么意思

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  

首先,我想你的意思是:

dictionary[word]+=1
而不是
input\u str[word]+=1
,但这不是执行此任务的方式。它还将引发
KeyError
异常

对于这样的任务,您可以简单地使用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()
函数作为
较低的句子.count(word)
。而且效果很好。@Moh'dH欢迎,是的,您可以使用
count
方法,但是
Counter
对于长字符串更有效!