Class: Nameko::Mecab

Inherits:
Object
  • Object
show all
Extended by:
FFI::Library
Defined in:
lib/nameko/nameko.rb

Overview

This class is providing a parse method.

 require 'nameko'

 mecab = Nameko::Mecab.new
 mecab.parse("私以外私じゃないの")
# =>
[
  #<MecabNode:0x00007f8f51117348>,
  #<MecabNode:0x00007f8f51116d30>,
  #<MecabNode:0x00007f8f51115610>,
  #<MecabNode:0x00007f8f51115138>,
  #<MecabNode:0x00007f8f51123fa8>,
  #<MecabNode:0x00007f8f51123be8>
]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(option = '') ⇒ Mecab

Initialize the mecab tagger with the given option.

How to specify options is as follows:

Examples:

mecab = Nameko::Mecab.new("-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd")
mecab = Nameko::Mecab.new(["-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd"])
mecab = Nameko::Mecab.new(["-d", "/usr/local/lib/mecab/dic/mecab-ipadic-neologd"])


45
46
47
48
49
50
# File 'lib/nameko/nameko.rb', line 45

def initialize(option = '')
  option = option.join(' ') if option.is_a? Array

  @mecab = mecab_new2(option)
  ObjectSpace.define_finalizer(self, Mecab.destroy(@mecab))
end

Class Method Details

.destroy(mecab) ⇒ Object



29
30
31
32
33
# File 'lib/nameko/nameko.rb', line 29

def self.destroy(mecab)
  proc {
    mecab_destory(mecab)
  }
end

Instance Method Details

#parse(str) ⇒ Array<MecabNode>

Parse the given string by MeCab.

Examples:

node = mecab.parse("私以外私じゃないの")[0]

node.surface # => "私"
node.feature #=> {:pos=>"名詞", :pos1=>"代名詞", :pos2=>"一般", :pos3=>"", :conjugation_form=>"", :conjugation=>"", :base=>"私", :yomi=>"ワタシ", :pronunciation=>"ワタシ"}
node.posid #=> 59
node.id #=> 1

Parameters:

  • str (String)

    Parsed text

Returns:

  • (Array<MecabNode>)

    Result of Mecab parsing



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/nameko/nameko.rb', line 65

def parse(str)
  node = MecabNode.new mecab_sparse_tonode(@mecab, str)
  result = []

  while !node.null? do
    if node.surface.empty?
      node = node.next
      next
    end
    result << node
    node = node.next
  end

  result
end