👩💻
言語処理100本ノック 2020 (Rev 2) 第4章: 形態素解析 35. 単語の出現頻度
問題
35. 単語の出現頻度
文章中に出現する単語とその出現頻度を求め,出現頻度の高い順に並べよ.
solution35.py
import itertools
from collections import Counter
from collections import defaultdict
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
filename = 'chapter04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
filtered_blocks = list(filter(lambda x: x != '', blocks))
parse_blocks = [parse_mecab(block) for block in filtered_blocks]
flat = list(itertools.chain.from_iterable(parse_blocks))
flat = [f["base"] for f in flat if f["pos"]!="記号"]
words = Counter(flat)
word_freq = words.most_common()
print(word_freq[:30])
output
[('の', 9194), ('て', 6848), ('は', 6420), ('に', 6243), ('を', 6071), ('だ', 5972), ('と', 5508), ('が', 5337), ('た', 4267), ('する', 3657), ('ない', 3052), ('も', 2479), ('ある', 2320), ('*', 2191), ('で', 2084), ('から', 2031), ('いる', 1777), ('ん', 1568), ('か', 1529), ('云う', 1408), ('事', 1207), ('です', 1164), ('ます', 1146), ('なる', 1120), ('へ', 1034), ('う', 987), ('もの', 981), ('君', 973), ('主人', 932), ('ぬ', 719)]
この問題では、各ブロックの形態素解析の結果から出現頻度の高い単語を出力します。まず parse_blocks
変数には、filtered_blocks
の各要素に対して、 parse_mecab
関数を適用した結果が格納されます。itertools.chain.from_iterable
関数を使用し、parse_blocks
の要素を一つのリストにflat
リストにpos
が記号
でない要素のbase
を追加します。collections.Counter
クラスを使用し、flat
リスト内の単語の出現回数を数えます。word_freq
変数に、words
から出現頻度が高い順に単語を取得します。
Discussion