2014-11-21 105 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 
相關問題