2012-03-29 18 views
7

長い文字列を解析して、各単語がPythonで出現する回数を計算しています。私は動作する関数を持っていますが、私はそれをより効率的に(速度の点で)できるかどうか、そして私にこれを行うことができるPythonのライブラリ関数があるかどうかについてのアドバイスを探していますので、 ?文字列の単語頻度を効率的に計算する

長い文字列(通常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)] 
関連する問題