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
对于长字符串更有效!