2012-03-29 5 views
7

저는 긴 문자열을 구문 분석하고 각 단어가 파이썬에서 발생하는 횟수를 계산합니다. 나는 작동하는 함수를 가지고 있지만, 속도면에서 더 효율적으로 만들 수있는 방법이 있는지, 그리고 내가 이것을 할 수있는 파이썬 라이브러리 함수가있을 지에 대한 조언을 찾고있다. 그래서 나는 바퀴를 재발 명하지 않는다. ?문자열의 단어 빈도를 효율적으로 계산하십시오.

긴 문자열 (일반적으로 문자열의 1000 단어 이상)에서 발생하는 가장 일반적인 단어를 계산하는보다 효율적인 방법을 제안 할 수 있습니까?

1 요소는 가장 일반적인 단어 목록에 사전을 정렬하는 가장 좋은 방법, 두 번째 요소는 2 번째로 가장 일반적인 단어 등이다 또한 뭐죠?

test = """abc def-ghi jkl abc 
abc""" 

def calculate_word_frequency(s): 
    # Post: return a list of words ordered from the most 
    # frequent to the least frequent 

    words = s.split() 
    freq = {} 
    for word in words: 
     if freq.has_key(word): 
      freq[word] += 1 
     else: 
      freq[word] = 1 
    return sort(freq) 

def sort(d): 
    # Post: sort dictionary d into list of words ordered 
    # from highest freq to lowest freq 
    # eg: For {"the": 3, "a": 9, "abc": 2} should be 
    # sorted into the following list ["a","the","abc"] 

    #I have never used lambda's so I'm not sure this is correct 
    return d.sort(cmp = lambda x,y: cmp(d[x],d[y])) 

print calculate_word_frequency(test) 
+0

'has_key'이되지 않습니다. 대신'key in d'를 사용하십시오. 또한, 정렬 함수는 꽤 잘못되었습니다. 'return sorted (d, key = d .__ getitem__, reverse = True)'는 빈도별로 내림차순 정렬을 수행하고 키를 반환합니다. – agf

답변

24

사용 collections.Counter는 :

>>> from collections import Counter 
>>> test = 'abc def abc def zzz zzz' 
>>> Counter(test.split()).most_common() 
[('abc', 2), ('zzz', 2), ('def', 2)] 
4
>>>> test = """abc def-ghi jkl abc 
abc""" 
>>> from collections import Counter 
>>> words = Counter() 
>>> words.update(test.split()) # Update counter with words 
>>> words.most_common()  # Print list with most common to least common 
[('abc', 3), ('jkl', 1), ('def-ghi', 1)] 
2

또한 NLTK (자연 언어 툴킷)를 사용할 수 있습니다. 텍스트 처리 연구를위한 아주 멋진 도서관을 제공합니다. 이 예를 들어, 당신은 사용할 수 있습니다

from nltk import FreqDist 

text = "aa bb cc aa bb" 
fdist1 = FreqDist(text) 

# show most 10 frequent word in the text 
print fdist1.most_common(10) 

결과가 될 것입니다 :

[('aa', 2), ('bb', 2), ('cc', 1)] 
관련 문제