Class: Spacy::PhraseMatcher

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

Overview

See also spaCy Python API document for PhraseMatcher. PhraseMatcher is useful for efficiently matching large terminology lists. It's faster than Matcher when matching many phrase patterns.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nlp, attr: "ORTH") ⇒ PhraseMatcher

Creates a Spacy::PhraseMatcher instance.

Examples:

Case-insensitive matching

matcher = Spacy::PhraseMatcher.new(nlp, attr: "LOWER")

Parameters:

  • nlp (Language) —

    an instance of Language class

  • attr (String) (defaults to: "ORTH") —

    the token attribute to match on (default: "ORTH"). Use "LOWER" for case-insensitive matching.



940
941
942
943
# File 'lib/ruby-spacy.rb', line 940

def initialize(nlp, attr: "ORTH")
  @nlp = nlp
  @py_matcher = PyPhraseMatcher.call(nlp.py_nlp.vocab, attr: attr)
end

Instance Attribute Details

#nlp ⇒ Language (readonly)

Returns the language model used by this matcher.

Returns:

  • (Language) —

    the language model used by this matcher



932
933
934
# File 'lib/ruby-spacy.rb', line 932

def nlp
  @nlp
end

#py_matcher ⇒ Object (readonly)

Returns a Python PhraseMatcher instance accessible via PyCall.

Returns:

  • (Object) —

    a Python PhraseMatcher instance accessible via PyCall



929
930
931
# File 'lib/ruby-spacy.rb', line 929

def py_matcher
  @py_matcher
end

Instance Method Details

#add(label, phrases) ⇒ Object

Adds phrase patterns to the matcher.

Examples:

Add product names

matcher.add("PRODUCT", ["iPhone", "MacBook Pro", "iPad"])

Parameters:

  • label (String) —

    a label string given to the patterns

  • phrases (Array<String>) —

    an array of phrase strings to match



950
951
952
953
# File 'lib/ruby-spacy.rb', line 950

def add(label, phrases)
  patterns = phrases.map { |phrase| @nlp.py_nlp.call(phrase) }
  @py_matcher.add(label, patterns)
end

#match(doc) ⇒ Array<Span>

Execute the phrase match and return matching spans.

Examples:

Find matches

matches = matcher.match(doc)
matches.each { |span| puts "#{span.text} => #{span.label}" }

Parameters:

  • doc (Doc) —

    a Doc instance to search

Returns:

  • (Array<Span>) —

    an array of Span objects with labels



961
962
963
964
# File 'lib/ruby-spacy.rb', line 961

def match(doc)
  py_matches = @py_matcher.call(doc.py_doc, as_spans: true)
  PyCall::List.call(py_matches).map { |py_span| Span.new(doc, py_span: py_span) }
end