计算每个单词在字符串中重复的次数?

时间:2014-11-21 19:09:57

标签: python dictionary

例如,如果我有一个没有任何标点符号的字符串:

"She walked the dog to the park and played ball with the dog When she threw the ball to the dog the dog missed the ball and ran to the other side of the park to fetch it"

我知道如何通过将字符串转换为大写/小写并使用函数

来实现
from collections import Counter

但是如果不使用内置函数(包括set.default,get,sorted等),我想不出任何其他计算方法。

它应该以密钥:值格式出现。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

忘记库和“快速”方法,使用更简单的逻辑:

首先使用stringName.split()拆分字符串。这将返回一个单词数组。现在创建一个空的dicitonary。然后遍历数组并执行以下两项操作之一(如果它存在于字典中),将计数递增1,否则,使用key创建键值对作为单词和值为1。

最后,你会有一些单词。

代码:

testString = "She walked the dog to the park and played ball with the dog When she threw the ball to the dog the dog missed the ball and ran to the other side of the park to fetch it"

dic = {}

words = testString.split()

for raw_word in words:
    word = raw_word.lower()
    if word in dic:
        dic[word] += 1
    else:
        dic[word] = 1

print dic