• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

python sudachi

date: 2024-12-15 excerpt: pythonでsudachiを使う

tag: javapythonsudachinlp


pythonでsudachiを使う

概要

  • sudachiはワークスアプリケーションズが開発した形態素解析器
  • pythonでSudachiを使うため, sudachipyがある(archived)
  • 元の実装系はJavaである

動作例

$ echo "ライオンの隠れ家" | java -jar sudachi-0.7.5.jar -s '{"systemDict":"system_full.dic"}'
ライオンの隠れ家        名詞,固有名詞,一般,*,*,*        ライオンの隠れ家
EOS
  • ライオンの隠れ家 は 2024年10月に放送されたオリジナルドラマ

pythonでの利用例(プロセス間の通信)

from subprocess import PIPE, Popen

class SudachiInteractive:
    def __init__(self, jar_path: str, config: str):
        """
        初期化時にSudachiのプロセスを起動する。
        :param jar_path: SudachiのJARファイルのパス
        :param config: Sudachiの設定ファイル(JSON文字列)
        """
        self.jar_path = jar_path
        self.config = config
        self.proc = None

    def __enter__(self):
        """
        Sudachiプロセスを起動する。
        """
        self.proc = Popen(
            ["java", "-jar", self.jar_path, "-s", self.config],
            stdin=PIPE,
            stdout=PIPE,
            stderr=PIPE,
            text=True,
        )
        return self

    def analyze(self, text: str):
        """
        形態素解析を実行。
        :param text: 解析対象の文字列
        :return: 形態素解析結果(リスト形式)
        """
        if not self.proc or self.proc.stdin.closed:
            raise RuntimeError("Process is not running or stdin is closed.")
        
        # 入力文字列を送信
        self.proc.stdin.write(text + "\n")
        self.proc.stdin.flush()

        # 結果を収集
        results = []
        while True:
            line = self.proc.stdout.readline()
            if not line or line.strip() == "EOS":  # EOSで終了
                break
            results.append(line.strip())

        return results

    def __exit__(self, exc_type, exc_value, traceback):
        """
        プロセスを終了する。
        """
        if self.proc:
            self.proc.stdin.close()
            self.proc.terminate()
            self.proc.wait()


# Sudachi JARファイルのパスと設定
jar_path = "sudachi-0.7.5.jar"
config = '{"systemDict":"system_full.dic"}'

# with文でSudachiを利用
with SudachiInteractive(jar_path, config) as sudachi:
    result = sudachi.analyze("ライオンの隠れ家が面白かった")
    print("解析結果:")
    for line in result:
        print(line)
"""
解析結果:
ライオンの隠れ家	名詞,固有名詞,一般,*,*,*	ライオンの隠れ家
が	助詞,格助詞,*,*,*,*	が
面白かっ	形容詞,一般,*,*,形容詞,連用形-促音便	面白い
た	助動詞,*,*,*,助動詞-タ,終止形-一般	た
"""


javapythonsudachinlp Share Tweet