目次
インストール
NuGet で「MeCab.DotNet」をインストールします。 MeCab.DotNet は「MeCab」、「NMeCab」を .NET Core に移植したパッケージです。
以下パッケージサイトから抜粋。
"MeCab" は、日本語形態素解析エンジンのプロジェクトです。
"NMeCab" は、上記MeCabを、.NET Framework 2.0のマネージライブラリとして実装し直したものです。ただ、もう更新されていないようです...
"MeCab.DotNet" (このプロジェクト)は、上記NMeCabを最新の.NET Core 1/2/3と.NET Frameworkで使えるように移植し、NuGetのパッケージに固めて使いやすくしたものです。
なお、ライセンスは GPL2 または LGPL2.1 とのことで利用に際しては注意が必要です。
サンプル実装
WPFのサンプル実装です。
<Window x:Class="Samples.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:MeCab" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <TextBox x:Name="textbox" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,10,150,0" TextWrapping="Wrap" Width="600" AcceptsReturn="True"/> <Button Content="解析" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="620,10,0,0" Width="75" Click="Button_Click"/> <TextBlock x:Name="result" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,40,10,0" /> </Grid> </Window>
コードビハインド
using MeCab; using System.Windows; namespace Samples { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { var tagger = MeCabTagger.Create(); result.Text = ""; foreach(var node in tagger.ParseToNodes(textbox.Text)) { if (0 < node.CharType) { result.Text += $"{node.Surface}\t{node.Feature}\r\n"; } } } } }
実行結果は次の通り。