Skip to content

Instantly share code, notes, and snippets.

@kiyukuta
Last active December 22, 2015 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiyukuta/6437670 to your computer and use it in GitHub Desktop.
Save kiyukuta/6437670 to your computer and use it in GitHub Desktop.
MeCabの出力形式として,各形態素の基本形を出力として用いた分かち書きを行うオプション,"wakati_lemma"を追加するパッチ. 未知語については表層形をそのまま出力する.
<訂正>

こちらの記事に,同じ話題をより良い方法で実現する方法があると教えていただきました.↲

MeCabの出力フォーマット - 唯物是真 @Scaled_Wurm

公式の 出力フォーマット一覧 も改めて見たらちゃんと乗ってました,流し読みしてしまっていた...

ちなみに自分のブログ元記事は こちら

MeCabの出力形式として,各形態素の基本形を出力として用いた分かち書きを行うオプション,"wakati_lemma"を追加するパッチ. 未知語については表層形をそのまま出力する.

MeCab: Yet Another Part-of-Speech and Morphological Analyzer

src以下のwriter.cpp, writer.hに変更を加えている. 詳しくは,writer.patchを参照(+で始まっているが,僕の追加した行です.)

ほぼ関数を追加しただけなので変な事にはならないと思いますが,いちおう適用は自己責任でお願いします.

環境

mecab-0.996

適用方法

% cd path/to/mecab-0.996
% cd src
% wget https://gist.github.com/kiyukuta/6437670/raw/f1e1493a0ee7efabd2e7034801e7a44e7f945c6f/writer.patch
% patch < writer.patch
% cd ..
% make作業(詳しくは公式へ)

実行例

% echo "諦めんなよ!" | mecab -Owakati
諦めん な よ !                                       
% echo "諦めんなよ!" | mecab -Owakati_lemma
諦める な よ !
--- writer.cpp 2013-09-04 16:36:36.891234812 +0900
+++ writer-new.cpp 2013-09-04 16:52:30.244444509 +0900
@@ -34,6 +34,8 @@
write_ = &Writer::writeDump;
} else if (ostyle == "em") {
write_ = &Writer::writeEM;
+ } else if (ostyle == "wakati_lemma") { // wakati_lemma
+ write_ = &Writer::writeWakatiLemma;
} else {
// default values
std::string node_format = "%m\\t%H\\n";
@@ -132,6 +134,25 @@
*os << ' ';
}
*os << '\n';
+ return true;
+}
+
+bool Writer::writeWakatiLemma(Lattice *lattice, StringBuffer *os) const {
+ for (const Node *node = lattice->bos_node()->next;
+ node->next; node = node->next) {
+
+ if(node->stat == MECAB_UNK_NODE){
+ os->write(node->surface, node->length);
+ *os << ' ';
+ continue;
+ }
+ std::string features = std::string(node->feature);
+ int end = features.rfind(',', features.rfind(',') - 1);
+ int bgn = features.rfind(',', end - 1) + 1;
+ *os << features.substr(bgn, end-bgn);
+ *os << ' ';
+ }
+ *os << '\n';
return true;
}
--- writer.h 2013-09-04 16:36:36.898345616 +0900
+++ writer-new.h 2013-09-04 16:06:44.052467168 +0900
@@ -49,6 +49,7 @@
bool writeUser(Lattice *lattice, StringBuffer *s) const;
bool writeDump(Lattice *lattice, StringBuffer *s) const;
bool writeEM(Lattice *lattice, StringBuffer *s) const;
+ bool writeWakatiLemma(Lattice *lattice, StringBuffer *s) const;
bool (Writer::*write_)(Lattice *lattice, StringBuffer *s) const;
};
@mocyuto
Copy link

mocyuto commented Sep 4, 2013

これは!
pythonでパースしてたのが、ばかみたいだ!

@kiyukuta
Copy link
Author

kiyukuta commented Sep 4, 2013

しかし,このくらいの操作はオプションで実現できることが判明したので追記しておきました!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment