👩‍💻

# 言語処理100本ノック 2020 (Rev 2) 第4章: 形態素解析 39. Zipfの法則

2023/01/11に公開約1,600字

### 問題

#### 39. Zipfの法則

solution39.py
``````# Plot a log-log graph with the x-axis being rank order and the y-axis being frequency.
import itertools
from collections import Counter
from collections import defaultdict
import matplotlib.pyplot as plt
import japanize_matplotlib

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:

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()

rank = range(1, len(word_freq)+1)
plt.figure()
plt.scatter(rank, dict(word_freq).values())
plt.xscale("log")
plt.yscale("log")
plt.xlabel("頻度順位")
plt.ylabel("頻度")
plt.show()
``````

output

この問題では、各ブロックの形態素解析の結果から、単語の出現頻度順位を横軸、その出現頻度を縦軸として、両対数グラフを作成します。

ログインするとコメントできます