2011-11-25 457 views
3

所以我一直在學習Python幾個月,並想知道如何去寫一個函數來計算一個單詞在一個句子中出現的次數。我將不勝感激,如果有人能告訴我一步一步的方法,這樣做如何計算一個單詞在一個句子中出現的次數? (Python)

謝謝

+1

[http://stackoverflow.com/search?q= \ [python \] + count + words](http://stackoverflow.com/search?q=count+words+%5Bpython%5D) – NullUserException

+5

定義「句子」和「單詞」。此外,如果你已經學習了幾個月,你應該能夠*開始*(不一定完成,但試試看)自己寫一個函數... – delnan

回答

5

快速回答:

def count_occurrences(word, sentence): 
    return sentence.lower().split().count(word) 

'some string.split()將拆分上空白的字符串(空格,製表符和換行符)列入一個字的事情列表。然後['some', 'string'].count(item)返回列表中出現item的次數。

這不處理刪除標點符號。你可以使用string.maketransstr.translate來做到這一點。

# Make collection of chars to keep (don't translate them) 
import string 
keep = string.lowercase + string.digits + string.whitespace 
table = string.maketrans(keep, keep) 
delete = ''.join(set(string.printable) - set(keep)) 

def count_occurrences(word, sentence): 
    return sentence.lower().translate(table, delete).split().count(word) 

這裏的關鍵是,我們已經構建了串delete,使其包含除字母,數字和空格的所有ASCII字符。然後str.translate在這種情況下需要一個不會更改字符串的轉換表,而且還會刪除一串字符。

+0

string.translate技術上在已棄用的文檔部分,因此我會謹慎使用該功能作爲一種習慣。 – Aurora

+1

你是對的 - 我改變了文本來引用str.translate,這是做這件事的幸運方式。 – babbageclunk

+0

使用術語「祝福的方式」的+1 +1 – Aurora

3

威爾伯福斯擁有快速,正確的答案,並且我會給出冗長的「如何得出結論」的答案。

首先,這裏有一些工具可以幫助你開始,還有一些問題你需要問自己。

你需要閱讀python文檔中的Sequence Types這一節,因爲它是解決這個問題的最好的朋友。認真閱讀。一旦你讀完了,你應該有一些想法。例如,你可以用一個很長的字符串並使用split()函數來分解它。要明確:

mystring = "This sentence is a simple sentence." 
result = mystring.split() 
print result 
print "The total number of words is: " + str(len(result)) 
print "The word 'sentence' occurs: " + str(result.count("sentence")) 

接受輸入字符串,並分割其上的任何空白,並會給你:

["This", "sentence", "is", "a", "simple", "sentence."] 
The total number of words is 6 
The word 'sentence' occurs: 1 

現在在這裏指出,你有周期仍然在第二年底'句子'。這是一個問題,因爲'句子'與'句子'不一樣。如果您要查看清單並計算單詞,則需要確保字符串完全相同。您可能需要找到並刪除一些標點符號。

一個naieve方法,這可能是:

no_period_string = mystring.replace(".", " ") 
print no_period_string 

爲了讓我在一段少一句:

"This sentence is a simple sentence" 

您還需要決定是否你的輸入將只是一個簡單的句子,或者可能是一段文字。如果你的輸入中有很多句子,你可能想要找到一種方法將它們分解成單獨的句子,並找到句號(或問號,或感嘆號或其他標點符號結尾的句子)。一旦你找到了字符串中的「句子終結符」,你可能會將分割成這個字符串,或者類似的東西。

你應該試一試自己 - 希望我已經有足夠的提示,讓你看看文檔中的一些特定功能。

+0

答案:「這個句子中有多少個單詞?」,但不是「這個單詞在這個句子中出現多少次?」。 :) – babbageclunk

+0

哦當。閱讀失敗。定影。 – Aurora

0

你可以這樣說:

def countWord(word): 

    numWord = 0 
    for i in range(1, len(word)-1): 
     if word[i-1:i+3] == 'word': 
      numWord += 1 
    print 'Number of times "word" occurs is:', numWord 

然後調用字符串:

countWord('wordetcetcetcetcetcetcetcword') 

將返回:Number of times "word" occurs is: 2

相關問題