Pythonは最も頻繁な単語のトップ10を数えます



Python Counts Top Ten Most Frequent Words



1.説明

これはPythonのインタビューの質問です:



'読み取り可能なファイルには10,000行あり、1行に1つの単語しかありません。言葉を繰り返すことができます。この10,000行で最も頻繁に出現する上位10語を見つけます。「」




第二に、アイデア

最初にファイルをリストに読み込み、次にセットを使用して複製して参照リストを取得し、逆ソートして上位10個(最大は最大10個の要素)を取得し、参照リストの各要素を使用してからカウントします。ファイル、参照リストの要素をキーとして使用します。統計結果は値であり、辞書に入れて印刷します。




第三に、コード

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #!/usr/bin/python #coding:utf-8 all_C = [] with open('words.txt','r') as f:for line in f.readlines():all_C.append(line) #Get no duplicate elements all_set=set(sorted(all_C)) #Statistics as a dictionary counts={} for key in all_set:counts[key] = all_C.count(key) #Get the number of the first 10 elements into a list tens = sorted(counts.values(),reverse=True)[0:11] print tens #Statistics on the last ten elements and the number of occurrences tendict = {} for k in counts.keys():if counts[k] in tens:tendict.setdefault(counts[k],k.strip(' ')) print('The 10 most frequently occurring words are: %s ') %tendict


#python tens.py

示されているように:

wKioL1nN5o_xRcELAAGkpo338gw245.png

練習ファイルは次の10001行に似ていますが、ファイルとして読み取るのは非常に高速です。

wKioL1nN50vCAnEpAAMEGH1zANI990.png


他の人のコード2を参照してください。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 #!/usr/bin/python #coding:utf-8 result= {} with open('words.txt','r') as fopen:fopen.seek(0, 2)all = fopen.tell()fopen.seek(0,0)while fopen.tell() <all:lines = fopen.readline().strip()if lines in result:result[lines] += 1else:result[lines] = 1 print(sorted(result.items(),key=lambda k:k[1],reverse=True)[:11])

実行結果を図に示します。

wKioL1nbUTCTID2hAAFlGKj6FLM140.png

総括する:

私は自分で少し低く書いたのは完全に練習です、2番目の方法はより高いです!もっと良い方法はありますか?










この記事は、元のリンクであるdyc2005 51CTOブログから転送されています:http://blog.51cto.com/dyc2005/1969699、再版が必要な場合は、元の作成者に連絡してください