2014-10-02 3 views
2

저는 파이썬으로 새로운데 이것을 해결하는 방법을 모르겠습니다 : 단어가 텍스트에 나타나는 횟수를 계산하는 함수를 작성하십시오. 이것은 지금까지의 코드입니다.하지만 막혔습니다. 나는 단어로 텍스트를 분할하는 방법을 찾을 필요가 있다고 생각하지만 목록에있어 나는 이렇게 할 수 없다. 개별 단어의 각 행 split 전달 사전단어가 텍스트에있는 횟수를 계산하는 방법

+0

()가 바로 다음 분할 전화를 받아 하나의 큰 문자열을 얻기 위해() 읽습니까, 라인의 목록을 얻을 수 있습니다(). – PaulMcG

+0

https://docs.python.org/2/library/string.html#string.count –

+0

한 단어 만 집계하면됩니다 :'f.read(). count (word)'. 대소 문자를 구별하지 않는다 :'f.read(). upper(). count (word.upper())'. –

답변

2

사용 collections.Counter에서

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 

감사합니다. 대신 readlines 메쏘드를 사용

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) 
관련 문제