2014-10-02 60 views
2

我是python中的新成員,我不知道如何解決這個問題:編寫一個函數來計算單詞在文本中出現的次數。這是我的代碼,但我卡住了。我想我需要找到一種方法來分離文本中的文字,但它在列表中,所以我不能這樣做。如何計算單詞在文本中的次數

def searcher(file): 
    f = open(file,"r") 
    word = raw_input("Write your word: ") 
    text = f.readlines() 
    text1 = text.split() 
    counter = 0 
    for x in text1: 
     if x == word: 
      counter = counter +1 
    print counter 

在此先感謝

+0

而不是使用readlines()來獲取行列表,只需read()以獲得一個大字符串,然後它將接受對split()的調用。 – PaulMcG 2014-10-02 18:15:11

+0

請考慮https://docs.python.org/2/library/string.html#string.count – 2014-10-02 18:16:13

+0

如果您只需計算一個單詞:'f.read()。count(word)'。不區分大小寫:'f.read()。upper()。count(word.upper())'。 – 2014-10-02 18:17:41

回答

2

使用collections.Counter通過在單個單詞每行split

s = "foo foo foobar bar" 
from collections import Counter 
print Counter(s.split()) 
Counter({'foo': 2, 'foobar': 1, 'bar': 1}) 

def searcher(file): 
    c = Counter() 
    word = raw_input("Write your word: ") 
    with open(file,"r") as f: 
     for line in f: 
      c.update(line.lower().rstrip().split()) 
    return c.get(word) 
相關問題