MeCab.exe を呼び出して形態素解析をする - C#

C#のプログラムからMeCab.exe を呼び出して形態素解析を実行します。

事前準備

MeCabのインストールはこちら、実行はこちらの記事を参照してください。。

概要

動作の仕組みは、コンソールアプリケーションのMeCab.Exeを実行し標準入力で形態素解析したいテキストを入力し、その結果を非同期で受け取ります。コンソールアプリケーションの出力を非同期で受け取る方法はこちらの記事で解説しています。
DLLを呼び出す方法は使わないのか?
C#のプログラムをAnyCPUでビルドし、Windowsのx64環境で動作させた場合は、DLL(Mecab.dll)も64ビットでコンパイルする必要があるため、exeファイルを実行する方法を紹介しています。

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;

namespace MeCabCall
{
  public partial class FormMain : Form
  {
    public delegate void MyEventHandler(object sender, DataReceivedEventArgs e);
    public event MyEventHandler myEvent = null;
    Process process = null;
    StreamWriter sw = null;
        
    public FormMain()
    {
      InitializeComponent();
    }

    private void button_StartExec_Click(object sender, EventArgs e)
    {
      myEvent = new MyEventHandler(event_DataReceived);

      process = new Process();
      process.StartInfo.FileName = @"C:\Program Files (x86)\MeCab\bin\Mecab.exe";
      //process.StartInfo.Arguments = "-h";

      process.StartInfo.UseShellExecute = false;
      process.StartInfo.RedirectStandardOutput = true; // 標準出力をリダイレクト
       process.OutputDataReceived += new DataReceivedEventHandler(process_DataReceived);

      process.StartInfo.RedirectStandardInput = true;

      process.Start();
      process.BeginOutputReadLine();

      sw = process.StandardInput;
      sw.AutoFlush = true;
      sw.WriteLine(textBox1.Text);
    } 

    private void button_Exec_Click(object sender, EventArgs e)
    {
      sw.WriteLine(textBox1.Text);
    }

    void event_DataReceived(object sender, DataReceivedEventArgs e)
    {
      textBox2.Text += e.Data + "\r\n";
    }

    void process_DataReceived(object sender, DataReceivedEventArgs e)
    {
      //Console.WriteLine(e.Data);  
      this.Invoke(myEvent, new object[2] { sender, e });
    }
  }
}

解説

下記のコードでプロセスを作成し、MeCab.exeを指定します。
 process = new Process();
 process.StartInfo.FileName = @"C:\Program Files (x86)\MeCab\bin\Mecab.exe";

UseShellExecuteプロパティをFalseに設定し、RedirectStandardOutputプロパティをTrueに設定しMeCabの出力をリダイレクトします。さらにOutputDataReceivedにイベントハンドラを設定し、MeCabの出力を非同期で読み取れる設定にします。
 process.StartInfo.UseShellExecute = false;
 process.StartInfo.RedirectStandardOutput = true;
 process.OutputDataReceived += new DataReceivedEventHandler(process_DataReceived);

RedirectStandardInputプロパティをTrueに設定し、MeCabへの入力をリダイレクトします。
 process.StartInfo.RedirectStandardInput = true;

プロセスを開始し、非同期読み込みを開始します。コンソールアプリケーションの非同期読み込みはこちらの記事を参照してください。
 process.Start();
 process.BeginOutputReadLine();

下記コードの標準入力でtextBox1の内容をMeCab.exeに入力します。
MeCab.exeが形態素解析を実行し、処理が完了し標準出力で結果を出力するとprocess_DataReceived()メソッドが呼び出されます。process_DataReceivedメソッドは他のスレッドから呼び出されるため、Invokeメソッドを用いてスレッドの同期をとり、event_DataReceivedメソッドを呼び出します。event_DataReceived()メソッド内でtextBox2にMeCab.exeの形態素解析の結果を表示します。
 sw = process.StandardInput;
 sw.AutoFlush = true;
 sw.WriteLine(textBox1.Text);

2度目以降はすでにMeCab.exeが起動していますので、textBox1に形態素解析したい内容を入力し、button_ExecをクリックしてtextBox1の内容を標準入力に送るだけで結果がtextBox2に表示されます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-04
作成日: 2010-11-15
iPentec all rights reserverd.