开始使用免费开始使用

在 spaCy 中使用 EntityRuler 的 RegEx

正则表达式(RegEx)用于基于规则的信息抽取,支持复杂的字符串匹配。RegEx 可以用来检索模式,或将字符串中匹配的模式替换为其他模式。在本练习中,您将练习使用 spaCyEntityRuler 在给定的 text 中查找电子邮件地址。

已为您导入 spaCy 库。您可以使用 \d 来匹配元字符所代表的任意数字(0 到 9)。

spaCy 的模式可以把 REGEX 作为一个属性。在这种情况下,模式的形式为 [{"TEXT": {"REGEX": "<a given pattern>"}}]

本练习是课程的一部分

使用 spaCy 的自然语言处理

查看课程

练习说明

  • 定义一个用于 EntityRuler 的模式,以匹配形如 8888888888 的电话号码。
  • 加载一个空白的 spaCy 英语模型,并向管线添加一个 EntityRuler 组件。
  • 将编写好的模式添加到 EntityRuler 组件中。
  • 运行模型,并打印给定 text 中实体的文本与类型所组成的元组。

交互式实操练习

通过完成这段示例代码来试试这个练习。

text = "Our phone number is 4251234567."

# Define a pattern to match phone numbers
patterns = [{"label": "PHONE_NUMBERS", "pattern": [{"TEXT": {"REGEX": "(____){____}"}}]}]

# Load a blank model and add an EntityRuler
nlp = spacy.____("en")
ruler = nlp.____("entity_ruler")

# Add the compiled patterns to the EntityRuler
ruler.____(patterns)

# Print the tuple of entities texts and types for the given text
doc = ____(____)
print([(ent.____, ent.____) for ent in doc.____])
编辑并运行代码