在 spaCy 中使用扩展语法进行匹配
基于规则的信息抽取是任何 NLP 流水线的关键组成部分。Matcher 类允许在花括号中使用一些运算符,使得模式表达更灵活。这些运算符用于扩展比较,形式类似于 Python 的 in、not in 和比较运算符。本练习中,您将练习使用 spaCy 的匹配功能 Matcher,从示例文本中为给定词项找到匹配。
Matcher 类已从 spacy.matcher 库导入。您将在本练习中使用示例文本对应的 Doc 容器 doc。预加载的 spaCy 模型也可以通过 nlp 访问。
本练习是课程的一部分
使用 spaCy 的自然语言处理
练习说明
- 使用
Matcher和nlp定义一个 matcher 对象。 - 使用
IN运算符定义一个可以匹配tiny squares和tiny mouthful的模式。 - 使用该模式在
doc中查找匹配。 - 打印匹配的起始与结束 token 下标,以及匹配到的文本片段。
交互式实操练习
通过完成这段示例代码来试试这个练习。
nlp = spacy.load("en_core_web_sm")
doc = nlp(example_text)
# Define a matcher object
matcher = Matcher(nlp.____)
# Define a pattern to match tiny squares and tiny mouthful
pattern = [{"lower": ____}, {"lower": {____: ["squares", "mouthful"]}}]
# Add the pattern to matcher object and find matches
matcher.____("CustomMatcher", [____])
matches = ____(____)
# Print out start and end token indices and the matched text span per match
for match_id, start, end in matches:
print("Start token: ", ____, " | End token: ", ____, "| Matched text: ", doc[____:____].text)