【发布时间】: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