2014-11-21 69 views
0

例如,如果我有没有任何标点符号的字符串:计算每个单词在一个字符串中重复的次数?

"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等)的任何其他方式来计数

它应该以key:value格式出现。有任何想法吗?

回答

1

忘掉库和做它的“快”的方式,用简单的逻辑:

开始通过拆分使用stringName.split()的字符串。这返回给你一个单词的数组。现在创建一个空dicitonary。然后迭代数组并执行以下两项操作之一(如果它存在于字典中,则将计数加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 
相关问题