开始使用免费开始使用

spaCy 中的 PhraseMatcher

在处理非结构化文本时,您常常需要在长列表或字典中扫描并匹配给定文本。Matcher 的模式需要手工编写,而且每个 token 都要单独编码。如果您有很长的短语列表,Matcher 就不再是最佳选择。在这种情况下,PhraseMatcher 类可以帮助我们匹配大型词典。在本练习中,您将练习使用 PhraseMatcher 类,通过匹配形状来检索多个术语的模式。

en_core_web_sm 模型已加载为 nlp,可以直接使用。PhraseMatcher 类已导入。一个字符串 text 和一个 terms 列表也已为您准备好。

本练习是课程的一部分

使用 spaCy 的自然语言处理

查看课程

练习说明

  • 使用 attr 初始化一个 PhraseMatcher,以匹配给定 terms 的形状。
  • 创建要添加到 PhraseMatcher 对象的 patterns
  • 查找给定模式的匹配,并打印开始与结束的 token 索引,以及在给定 text 中匹配到的片段。

交互式实操练习

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

text = "There are only a few acceptable IP addresse: (1) 127.100.0.1, (2) 123.4.1.0."
terms = ["110.0.0.0", "101.243.0.0"]

# Initialize a PhraseMatcher class to match to shapes of given terms
matcher = ____(nlp.____, attr = ____)

# Create patterns to add to the PhraseMatcher object
patterns = [nlp.make_doc(____) for term in terms]
matcher.____("IPAddresses", patterns)

# Find matches to the given patterns and print start and end characters and matches texts
doc = ____
matches = ____
for match_id, start, end in matches:
    print("Start token: ", ____, " | End token: ", ____, "| Matched text: ", doc[____:____].text)
编辑并运行代码