2013-08-14 3 views
-2

문자열 목록에 단어가 몇 번 나왔는지 계산하는 방법은 무엇입니까? 예를 들어문자열 목록에서 단어 발생을 계산하십시오.

:

['This is a sentence', 'This is another sentence'] 

및 단어 "문장"에 대한 결과는 2

+0

아마도 루프를 시도 할 수 있습니까? 그리고'split()'? – thegrinner

+0

문제를 추적하는 데 도움이 될 수있는 첫 번째 시도가 붙여 넣을 수 있습니까? – JoshG79

+0

관련 항목 : [항목 빈도 카운트에서 파이썬] (http://stackoverflow.com/questions/893417/item-frequency-count-in-python) –

답변

9

collections.Counter() 개체를 사용하고 공백에 단어를 분할합니다. 지금 당신은 단어 당으로 counts 사전이

from collections import Counter 
import re 

counts = Counter() 
words = re.compile(r'\w+') 

for sentence in sequence_of_sentences: 
    counts.update(words.findall(sentence.lower())) 

:

from collections import Counter 

counts = Counter() 

for sentence in sequence_of_sentences: 
    counts.update(word.strip('.,?!"\'').lower() for word in sentence.split()) 

또는 아마도 유일한 단어 문자와 일치하는 정규 표현식을 사용 : 당신은 아마뿐만 아니라 당신의 단어를 소문자, 제거 구두점 할 카운트.

데모 :

>>> sequence_of_sentences = ['This is a sentence', 'This is another sentence'] 
>>> from collections import Counter 
>>> counts = Counter() 
>>> for sentence in sequence_of_sentences: 
...  counts.update(word.strip('.,?!"\'').lower() for word in sentence.split()) 
... 
>>> counts 
Counter({'this': 2, 'is': 2, 'sentence': 2, 'a': 1, 'another': 1}) 
>>> counts['sentence'] 
2 
+0

모든 구두점 기호를 쓰는 대신 첫 번째 정규식을 사용합니다. 장소. 're.findall ('\ w +', sentence)' –

+0

@OlehPrypin : 오, 그래, 좋은 생각이야. –

+0

@OlehPrypin 그 정규식의 문제점은'-'를 가진 단어를 고려하지 않는다는 것입니다. 2 단어로 계산됩니다. –

2

당신은 아주 쉽게 약간의 정규식과 사전에 원하는 것을 할 수 있습니다.

import re 

dict = {} 
sentence_list = ['This is a sentence', 'This is a sentence'] 
for sentence in sentence_list: 
    for word in re.split('\s', sentence): # split with whitespace 
     try: 
      dict[word] += 1 
     except KeyError: 
      dict[word] = 1 
print dict 
관련 문제