長い文字列を解析して、各単語が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)
'has_key'が推奨されていません。代わりに 'key in d'を使用してください。また、あなたのソート関数はかなり間違っています。 'return sorted(d、key = d .__ getitem__、reverse = True)'は頻度で降順ソートを行い、キーを返します。 – agf