Issue
Hi I am writing a lot of function with the following form:
def is_match_a(doc):
pattern = # spaCy patterns
matcher = Matcher(nlp.vocab)
matcher.add("match_a", [pattern])
matches = matcher(doc)
if matches:
return True
I want to write a function that generate these function from a given pattern and name. I am thinking something like:
def generate_matcher(pattern, name):
func = some code
return func
so that ultimately, I can do something the following
is_match_a = generate_matcher(pattern_a, name_a)
is_match_b = generate_matcher(pattern_b, name_b)
if is_match_a(doc):
# do something
elif is_match_b(doc):
# do something else
I am new to python and I can not wrap my head around how to go about this. Is this where you use decorator?
Solution
Define a nested function that uses the pattern
and name
parameters of the main function.
def generate_matcher(pattern, name):
def is_match(doc):
matcher = Matcher(nlp.vocab)
matcher.add(name, [pattern])
matches = matcher(doc)
if matches:
return True
return is_match
Answered By - Barmar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.