如何使用 SpaCy Matcher(或 PhraseMatcher)class 来提取 2 个项目的序列?

How can I use SpaCy Matcher (or PhraseMatcher) class for the extracting the sequence of 2 items?

我有以下任务:从文本中提取两个标记的组合。他们每个人都属于列表。例如:

colors=['red','gray','black','white','brown']
animals=['fox','bear','hare','squirrel','wolf']

在 SpaCy 文档 https://spacy.io/usage/rule-based-matching 中,很好地描述了如何匹配两个列表中的所有这些单词或如何匹配特定两个列表的顺序,例如:

pattern = [{"LOWER": "red"}, {"LOWER": "fox"}]

但我需要匹配任何组合,例如“红松鼠”或“白熊”。 我可以通过 SpaCy 中的 Matcher(或 PhraseMatcher)实现这一点,还是我需要使用任何额外的 python 模块? 有人有非法解决的想法吗?

在此先感谢您的帮助。

您也可以在 SpaCy 中使用正则表达式。例如,fr"(?i)^({'|'.join(colors)})$" 将创建一个以不区分大小写的方式匹配令牌的模式,该模式将匹配 colors 项中的任何一项。

import spacy
from spacy.matcher import Matcher

nlp = spacy.load("en_core_web_sm")

matcher = Matcher(nlp.vocab)

colors=['red','gray','black','white','brown']
animals=['fox','bear','hare','squirrel','wolf']
pattern = [
   {'TEXT': {"REGEX": fr"(?i)^({'|'.join(colors)})$"}},
   {'TEXT': {"REGEX": fr"(?i)^({'|'.join(animals)})$"}}
]
matcher.add("ColoredAnimals", None, pattern)

doc = nlp("Hello, red fox! Hello Black Hare! What's up whItE sQuirrel, brown wolf and gray bear!")
matches = matcher(doc)
for match_id, start, end in matches:
    string_id = nlp.vocab.strings[match_id]
    span = doc[start:end]
    print(match_id, string_id, start, end, span.text)

输出:

8757348013401056599 ColoredAnimals 2 4 red fox
8757348013401056599 ColoredAnimals 6 8 Black Hare
8757348013401056599 ColoredAnimals 12 14 whItE sQuirrel
8757348013401056599 ColoredAnimals 15 17 brown wolf
8757348013401056599 ColoredAnimals 18 20 gray bear

您可以直接使用正则表达式提取词组:

import re
colors=['red','gray','black','white','brown']
animals=['fox','bear','hare','squirrel','wolf']
pattern = fr"(?i)\b(?:{'|'.join(colors)})\s+(?:{'|'.join(animals)})\b"
doc_string = "Hello, red fox! Hello Black Hare! What's up whItE sQuirrel, brown wolf and gray bear!"
print ( re.findall(pattern, doc_string) )
# => ['red fox', 'Black Hare', 'whItE sQuirrel', 'brown wolf', 'gray bear']

Python demo

此处,non-capturing组用于不在结果列表中创建额外的项目,\s+匹配1个或多个空白字符,\b用作单词边界而不是 ^(字符串开头)和 $(字符串结尾)锚点。