Class: Spacy::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-spacy.rb

Overview

See also spaCy Python API document for Matcher.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nlp) ⇒ Matcher

Creates a Spacy::Matcher instance

Parameters:



314
315
316
# File 'lib/ruby-spacy.rb', line 314

def initialize(nlp)
  @py_matcher = PyMatcher.(nlp.vocab)
end

Instance Attribute Details

#py_matcherObject (readonly)

Returns a Python Matcher instance accessible via PyCall.

Returns:

  • (Object)

    a Python Matcher instance accessible via PyCall



310
311
312
# File 'lib/ruby-spacy.rb', line 310

def py_matcher
  @py_matcher
end

Instance Method Details

#add(text, pattern) ⇒ Object

Adds a label string and a text pattern.

Parameters:

  • text (String)

    a label string given to the pattern

  • pattern (Array<Array<Hash>>)

    sequences of text patterns that are alternative to each other



321
322
323
# File 'lib/ruby-spacy.rb', line 321

def add(text, pattern)
  @py_matcher.add(text, pattern)
end

#match(doc) ⇒ Array<Hash{:match_id => Integer, :start_index => Integer, :end_index => Integer}>

Execute the match.

Parameters:

  • doc (Doc)

    an Doc instance

Returns:

  • (Array<Hash{:match_id => Integer, :start_index => Integer, :end_index => Integer}>)

    the id of the matched pattern, the starting position, and the end position



328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/ruby-spacy.rb', line 328

def match(doc)
  str_results = @py_matcher.(doc.py_doc).to_s
  s = StringScanner.new(str_results[1..-2])
  results = []
  while s.scan_until(/(\d+), (\d+), (\d+)/)
    next unless s.matched
    triple = s.matched.split(", ")
    match_id = triple[0].to_i
    start_index = triple[1].to_i
    end_index = triple[2].to_i - 1
    results << {match_id: match_id, start_index: start_index, end_index: end_index}
  end
  results
end