LoginSignup
1
2

pythonでMeCabを使う

Last updated at Posted at 2023-11-28

MeCabのインストール

pythonでのインストール

install
pip install mecab-python3

PC本体のインストール

ここからダウンロードしてインストールするとwindowsの人は初期設定だと
C:\Program Files (x86)\MeCab\binmecab.exeがあるとおもいます

使ってみる

情報を出力

nomal.py
import MeCab

tagger = MeCab.Tagger("")
input = "記事を書く"
output = tagger.parse(input)

print(output)
出力
記事    名詞,一般,*,*,*,*,記事,キジ,キジ
を      助詞,格助詞,一般,*,*,*,を,ヲ,ヲ
書く    動詞,自立,*,*,五段・カ行イ音便,基本形,書く,カク,カク
EOS

わかち書き

わかち書き(わかちがき)とは、文章において語の区切りに空白を挟んで記述することである。分かち書き、分ち書き、別ち書き、分書とも表記する。分別書き、放ち書きとも。
wikipediaより

wakati.py
import MeCab

tagger = MeCab.Tagger("-O wakati")
input = "記事を書く"
output = tagger.parse(input)

print(output)
出力
記事 を 書く

品詞分類

品詞 品詞(細分類1) 品詞(細分類2) 品詞(細分類3) 活用形 基本形 読み 発音
node.py
import MeCab

tagger = MeCab.Tagger("")
input = "記事を書く"
node = tagger.parseToNode(input)

while node:
    elem = node.feature.split(",")
    print(elem)
    node = node.next
出力
['BOS/EOS', '*', '*', '*', '*', '*', '*', '*', '*']
['名詞', '一般', '*', '*', '*', '*', '記事', 'キジ', 'キジ']
['助詞', '格助詞', '一般', '*', '*', '*', 'を', 'ヲ', 'ヲ']
['動詞', '自立', '*', '*', '五段・カ行イ音便', '基本形', '書く', 'カク', 'カク']
['BOS/EOS', '*', '*', '*', '*', '*', '*', '*', '*']

応用

特定の品詞をスキップ

skip.py
import MeCab

tagger = MeCab.Tagger("")
input = "私は、記事を書くよ!"
node = tagger.parseToNode(input)

cansel_words = ["助詞","記号"]

while node:
    if node.surface != "":
        elem = node.feature.split(",")
        if elem[0] not in cansel_words:
            print(node.surface)
    node = node.next
出力
私
記事
書く

特定の品詞だけ

tokutei.py
import MeCab

tagger = MeCab.Tagger("")
input = "私は、記事を書くよ!"
node = tagger.parseToNode(input)

cansel_words = ["動詞"]

while node:
    if node.surface != "":
        elem = node.feature.split(",")
        if elem[0] in cansel_words:
            print(node.surface)
    node = node.next
出力
書く
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2