mecab-python3
とunidic-lite
をインストールしましょう。unidic
はMeCabで使える辞書です。もともと推奨されているのはipadic
という辞書ですが、mecab-ipadic-neologd
のリポジトリを見ると更新が止まっているようなのでunidic
を使います。$ pip install mecab-python3 unidic-lite
symbol not found
が出る場合$ python -c 'import MeCab'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Users/xxx/.pyenv/versions/xxx/lib/python3.11/site-packages/MeCab/__init__.py", line 10, in <module>
from . import _MeCab
ImportError: dlopen(/Users/xxx/.pyenv/versions/xxx/lib/python3.11/site-packages/MeCab/_MeCab.cpython-311-darwin.so, 0x0002): symbol not found in flat namespace '__ZN5MeCab11createModelEPKc'
homebrew
でmecab
をソースからビルドするオプションをつけてインストール(または再インストール)します。install
、再インストールはreinstall
$ brew install --build-from-source mecab
mecab-python3
をインストールします。(先にpip uninstall mecab-python3
しておきましょう)$ ARCHFLAGS='-arch arm64' pip install --compile --use-pep517 --no-cache-dir --force mecab-python3==1.0.5
python -c 'import MeCab'
するとエラーが表示されなくなります。mecab-python3
とunidic-lite
はインストールされている前提で進めます。mecab_sample.py
を作って、今回使うドキュメントの大きさを測ってみると以下のようになりました。f = open('./sample.md', 'r', encoding='utf-8')
content = f.read()
f.close()
print(f'Content size: {len(content.encode("utf-8"))}')
$ python mecab_sample.py
Content size: 26249
mecab_sample.py
に加筆していきましょう。import MeCab
f = open('./sample.md', 'r', encoding='utf-8')
content = f.read()
f.close()
print(f'Content size: {len(content.encode("utf-8"))}')
words = []
mecab = MeCab.Tagger()
for s in mecab.parse(content).splitlines():
if (
"名詞" in s
and "サ変可能" not in s
and "形状詞可能" not in s
and "副詞可能" not in s
and "数詞" not in s
and "代名詞" not in s
and "接尾辞" not in s
):
word = s.split()[0]
if len(word) == 1:
continue
if word == "こと":
continue
if word == "もの":
continue
if word == "とき":
continue
if word == "ところ":
continue
if word == "ため":
continue
if word == "たち":
continue
if word == "なし":
continue
if word == "代わり":
continue
words.append(s.split()[0])
unique_words = list(set(words))
print(f'Prased content size: {len(unique_words)}')
$ python mecab_sample.py
Content size: 26249
Parsed content size: 1279