Last active
August 29, 2015 14:12
-
-
Save dulao5/a11aa5052f5df3ac6b31 to your computer and use it in GitHub Desktop.
mecab-rubyのMeCab::Tagger#parseToNodeをEnumberatorする ref: http://qiita.com/dulao5/items/6e080a66655f2e28c8be
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
require "mecab" | |
node = MeCab::Tagger.new.parseToNode("すもももももももものうち") | |
while node | |
puts "#{node.surface}\t#{node.feature}" | |
node = node.next | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
require "MeCab" | |
module MeCab | |
class Tagger | |
# parseToNodeの別名(エイリアス)を作ってprivate化する | |
alias_method :parseToNode_org, :parseToNode | |
private :parseToNode_org | |
# parseToNodeを再定義する | |
def parseToNode(*args) | |
#オリジナルのparseToNodeを呼び出す | |
node = parseToNode_org(*args) | |
# NodeのArrayを作って返す | |
nodes = [] | |
while node | |
nodes.push(node) | |
node = node.next | |
end | |
nodes | |
end | |
end | |
end | |
if __FILE__ == $0 | |
nodes = MeCab::Tagger.new.parseToNode("俺、この戦争が終わったら結婚するんだ。") | |
# Array#eachが使える! | |
nodes.each do |node| | |
puts "#{node.surface}\t#{node.feature}" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
require "mecab" | |
module MeCab | |
class Tagger | |
# parseToNodeの別名(エイリアス)を作ってprivate化する | |
alias_method :parseToNode_org, :parseToNode | |
private :parseToNode_org | |
def parseToNode(*args) | |
#オリジナルのparseToNodeを呼び出す | |
node = parseToNode_org(*args) | |
return node unless block_given? | |
# NodeのEnumberatorを作って返す | |
while node | |
yield node | |
node = node.next | |
end | |
end | |
end | |
end | |
if __FILE__ == $0 | |
# Ruby風に使える | |
MeCab::Tagger.new.parseToNode("俺、この戦争が終わったら結婚するんだ。") {|node| | |
puts "#{node.surface}\t#{node.feature}" | |
} | |
# 古い使い方も出来る | |
node = MeCab::Tagger.new.parseToNode("すもももももももものうち") | |
while node | |
puts "#{node.surface}\t#{node.feature}" | |
node = node.next | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment