我想你可能想做:
for word in textInput.split():
...
目前,您只是迭代中的每个字符textInput
。因此,要迭代每个单词,我们必须首先将字符串拆分为单词数组。默认情况下.split()
在空格上分割,但您可以通过将分隔符传递给来更改它split()
.
另外,您需要检查该单词是否在您的字典中,而不是在原始字符串中。所以尝试:
if word in word_counter:
...
然后,查找出现次数最多的条目:
highest_word = ""
highest_value = 0
for k,v in word_counter.items():
if v > highest_value:
highest_value = v
highest_word = k
然后,只需打印出的值highest_word
and highest_value
.
要跟踪联系,只需保留最高单词的列表即可。如果我们发现出现次数更高,请清除列表并继续重建。这是到目前为止的完整程序:
textInput = "He likes eating because he likes eating"
word_counter = {}
for word in textInput.split():
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
highest_words = []
highest_value = 0
for k,v in word_counter.items():
# if we find a new value, create a new list,
# add the entry and update the highest value
if v > highest_value:
highest_words = []
highest_words.append(k)
highest_value = v
# else if the value is the same, add it
elif v == highest_value:
highest_words.append(k)
# print out the highest words
for word in highest_words:
print word