spaCy 的 Matcher 与 PhraseMatcher

使用 spaCy 的自然语言处理

Azadeh Mobasher

Principal Data Scientist

spaCy 中的 Matcher

 

  • 正则(RegEx)模式可能复杂、难读且难调试。
  • spaCy 提供可读、可用于生产的替代方案:Matcher 类。

 

import spacy
from spacy.matcher import Matcher

nlp = spacy.load("en_core_web_sm") doc = nlp("Good morning, this is our first day on campus.")
matcher = Matcher(nlp.vocab)
使用 spaCy 的自然语言处理

spaCy 中的 Matcher

 

  • 匹配结果包含匹配片段的起始结束词元索引。
pattern = [{"LOWER": "good"}, {"LOWER": "morning"}]

matcher.add("morning_greeting", [pattern])
matches = matcher(doc) for match_id, start, end in matches: print("Start token: ", start, " | End token: ", end, "| Matched text: ", doc[start:end].text)
>>> Start token:  0  | End token:  2 | Matched text:  Good morning
使用 spaCy 的自然语言处理

Matcher 的扩展语法

 

  • 定义匹配模式时可使用运算符。
  • 与 Python 的 innot in 和比较运算符类似

 

Attribute Value type Description
IN any type 属性值属于列表
NOT_IN any type 属性值属于列表
==, >=, <=, >, < int, float 用于相等/不等比较的运算符
使用 spaCy 的自然语言处理

Matcher 的扩展语法

  • 使用 IN 运算符同时匹配 good morninggood evening
doc = nlp("Good morning and good evening.")
matcher = Matcher(nlp.vocab)
pattern = [{"LOWER": "good"}, {"LOWER": {"IN": ["morning", "evening"]}}]
matcher.add("morning_greeting", [pattern])
matches = matcher(doc)
  • 使用 IN 的匹配输出
for match_id, start, end in matches:
    print("Start token: ", start, " | End token: ", end,
          "| Matched text: ", doc[start:end].text)
>>> Start token:  0  | End token:  2 | Matched text:  Good morning
Start token:  3  | End token:  5 | Matched text:  good evening
使用 spaCy 的自然语言处理

spaCy 中的 PhraseMatcher

 

  • PhraseMatcher 类用于在文本中匹配大量短语。

 

from spacy.matcher import PhraseMatcher
nlp = spacy.load("en_core_web_sm")
matcher = PhraseMatcher(nlp.vocab)
terms = ["Bill Gates", "John Smith"]
使用 spaCy 的自然语言处理

spaCy 中的 PhraseMatcher

  • PhraseMatcher 的输出包含匹配片段的起始结束词元索引
patterns = [nlp.make_doc(term) for term in terms]
matcher.add("PeopleOfInterest", patterns)

doc = nlp("Bill Gates met John Smith for an important discussion regarding importance of AI.")
matches = matcher(doc) for match_id, start, end in matches: print("Start token: ", start, " | End token: ", end, "| Matched text: ", doc[start:end].text)
>>> Start token:  0  | End token:  2 | Matched text:  Bill Gates
Start token:  3  | End token:  5 | Matched text:  John Smith
使用 spaCy 的自然语言处理

spaCy 中的 PhraseMatcher

  • 可使用 PhraseMatcherattr 参数
matcher = PhraseMatcher(nlp.vocab, attr = "LOWER")

terms = ["Government", "Investment"] patterns = [nlp.make_doc(term) for term in terms] matcher.add("InvestmentTerms", patterns) doc = nlp("It was interesting to the investment division of the government.")
matcher = PhraseMatcher(nlp.vocab, attr = "SHAPE")

terms = ["110.0.0.0", "101.243.0.0"] patterns = [nlp.make_doc(term) for term in terms] matcher.add("IPAddresses", patterns) doc = nlp("The tracked IP address was 234.135.0.0.")
使用 spaCy 的自然语言处理

Passons à la pratique !

使用 spaCy 的自然语言处理

Preparing Video For Download...