2016-07-15 4 views
3

파일의 특정 단어를 집계하고 싶습니다.파이썬에서 특정 단어 하나를 세는 방법?

예를 들어 파일에 '사과'가 몇 번이나 표시됩니까? '사과'와 '단어'를 대체하여

#!/usr/bin/env python 
import re 

logfile = open("log_file", "r") 

wordcount={} 
for word in logfile.read().split(): 
    if word not in wordcount: 
     wordcount[word] = 1 
    else: 
     wordcount[word] += 1 
for k,v in wordcount.items(): 
    print k, v 

,하지만 여전히 내 파일에있는 모든 단어를 계산 : 나는이 시도.

모든 조언을 주시면 감사하겠습니다. : 당신은 단지 하나의 단어의 발생을 걱정하기 때문에

+0

확인을위한 Counter 사전을 사용할 수 있습니다 15083119/python-find-the-a-word-in-a-file), [특정 단어를 파일에 포함] (http://stackoverflow.com/questions/29213458/count-specific- word-in-file-with) – davedwards

답변

7

당신은 단지 str.count()을 사용할 수 있습니다, 어떤 코너의 경우를 피하기 위해, 그러나

with open("log_file") as f: 
    contents = f.read() 
    count = contents.count("apple") 

같은 잘못 "applejack" 같은 단어를 계산, 나는 당신이 사용하는 것이 좋습니다 regex : 정규식에서

import re 

with open("log_file") as f: 
    contents = f.read() 
    count = sum(1 for match in re.finditer(r"\bapple\b", contents)) 

\b는 패턴이 시작되었는지, 문자열 w에 반대 (A 단어 경계에 종료 ithin 더 긴 끈).

6

한 단어 만 신경 쓰면 모든 단어 수를 추적하기 위해 사전을 만들 필요가 없습니다. 당신은 파일의 줄 단위를 반복하고 관심있는 단어의 발생을 찾을 수 있습니다.

#!/usr/bin/env python 

logfile = open("log_file", "r") 

wordcount=0 
my_word="apple" 
for line in logfile: 
    if my_word in line.split(): 
     wordcount += 1 

print my_word, wordcount 

을하지만, 당신은 또한 모든 단어를 계산하려면, 단지에 대한 계산 단어를 인쇄 할 수 있습니다 코드에 대한이 작은 변경 사항에 관심이있는 단어는 다음과 같이 작동해야합니다.

#!/usr/bin/env python 
import re 

logfile = open("log_file", "r") 

wordcount={} 
for word in logfile.read().split(): 
    if word not in wordcount: 
     wordcount[word] = 1 
    else: 
     wordcount[word] += 1 
# print only the count for my_word instead of iterating over entire dictionary 
my_word="apple" 
print my_word, wordcount[my_word] 
+1

이것은 "Hello, apple!"과 같은 문장에서 "apple"을 놓칠 것입니다. –

+0

그렇습니다. 그러나 문제는 그러한 문제가 처리되어야하는지에 대해서는 언급하지 않습니다. OP는 모든 단어를 세는 대신 코드가 수행하는 것처럼 해결책은 단 하나의 단어 만 계산해야한다고 내 대답은 그렇게합니다. 그러나 일치하는 코드의 종류를 지정하는 정규식 (간단한 if 대신)은 코드의 다른 부분을 변경하지 않고도 작동합니다. – Wajahat

0

이 단어는 단어 배열에서 단어의 개수를 계산하는 예제입니다. 나는 파일 판독기가 꽤 비슷하다고 가정하고있다. [- 파일에서 단어의 발생을 찾아 파이썬 (http://stackoverflow.com/ :

def count(word, array): 
    n=0 
    for x in array: 
     if x== word: 
      n+=1 
    return n 

text= 'apple orange kiwi apple orange grape kiwi apple apple' 
ar = text.split() 

print(count('apple', ar)) 
1

이러한 아웃이

from collections import Counter 

with open("log_file", "r") as logfile: 
    word_counts = Counter(logfile.read().split()) 

print word_counts.get('apple') 
-2
fi=open("text.txt","r") 
cash=0 
visa=0 
amex=0 
for line in fi: 
    k=line.split() 
    print(k) 
    if 'Cash' in k: 
     cash=cash+1 
    elif 'Visa' in k: 
     visa=visa+1 
    elif 'Amex' in k: 
     amex=amex+1 

print("# persons paid by cash are:",cash) 
print("# persons paid by Visa card are :",visa) 
print("#persons paid by Amex card are :",amex) 
fi.close() 
+0

스택 오버플로에 오신 것을 환영합니다! 코드가 문제를 해결한다고 생각하는 이유를 설명하기 위해 몇 가지 설명을 추가하십시오. – ekhumoro

관련 문제