2016-11-14 9 views
0

ファイル内の単語から辞書を作成する関数を作成しました。値はread_dictionaryという単語の頻度です。私は今、次のように見えるように、ファイルの上位3つの単語を出力する別の関数を作成しようとしています。 "fileNameの上位3つの単語は: 単語:数字 単語:数字 単語:数字"ファイルを読み込んで、Pythonで辞書を使って上位3ワードを取得する

これは私のコードが何であるかです:

def top_three_by_count(fileName): 

    freq_words = sorted(read_dictionary(f), key = read_dictionary(f).get, 
    reverse = True) 

    top_3 = freq_words[:3] 
    print top_3 
print top_three_by_count(f) 

答えて

0

あなたはcollections.Counterを使用することができます。

from collections import Counter 
def top_three_by_count(fileName): 
     return [i[0] for i in Counter(read_dictionary(fileName)).most_common(3)] 

実際には、read_dictionary()機能はまったく必要ありません。次のコードスニペットはあなたのためにすべてを行います。

with open('demo.txt','r') as f: 
    print Counter([i.strip() for i in f.read().split(' ')]).most_common(3) 
+0

空リストを返すことを続けます。 – djderik

+0

@djderik、 'print read_dictionary(f)'の出力はどうですか?あなたは有効な辞書を取得していますか? –

+0

はい辞書を出力します。そして、fileNameは関数を定義するときのプレースホルダーにすぎないので、関数が作成された後に実際のファイル名を挿入するだけです。この場合はfです。それはread_dictionaryの機能のために働いた – djderik

関連する問題