【问题标题】:All matches in a line : Spacy matcher一行中的所有匹配项:Spacy 匹配器
【发布时间】:2020-01-06 23:14:05
【问题描述】:

我正在寻找使用 Spacy 匹配器在一行中打印所有匹配项的解决方案

例子是这样的, 在这里我试图提取经验。

doc = nlp("1+ years of experience in XX, 2 years of experiance in YY")
pattern = [{'POS': 'NUM'}, {'ORTH': '+', "OP": "?"}, {"LOWER": {"REGEX": "years?|months?"}}]
matcher = Matcher(nlp.vocab)
matcher.add("Skills", None, pattern)
matches = matcher(doc)
pirnt(doc[matches[0][1]:matches[0][2]]

我在这里得到输出1+ years

但我正在寻找具有输出的解决方案 ['1+ years','2 years']

【问题讨论】:

  • 看起来这段代码只返回2 years

标签: python nlp spacy


【解决方案1】:

您应该将第一项指定为'LIKE_NUM': True

pattern = [{'LIKE_NUM': True}, {'ORTH': '+', "OP": "?"}, {"LOWER": {"REGEX": "(?:year|month)s?"}}]

我还将years?|months?(?:year|month)s? 签约,您甚至可以考虑使用^(?:year|month)s?$ 匹配完整的令牌字符串,但此时没有必要。

代码:

import spacy
from spacy.matcher import Matcher

nlp = spacy.load("en_core_web_sm")
matcher = Matcher(nlp.vocab)
pattern = [{'LIKE_NUM': True}, {'ORTH': '+', "OP": "?"}, {"LOWER": {"REGEX": "(?:year|month)s?"}}]
matcher.add("Skills", None, pattern)

doc = nlp("1+ years of experience in XX, 2 years of experiance in YY")

matches = matcher(doc)
for _, start, end in matches:
  print(doc[start:end].text)

输出:

1+ years
2 years

【讨论】:

  • 收缩打破了 1+(它是 matchet 两次)。保留原来的 {"LOWER": {"REGEX": "years?|months?"}} 并且它可以工作。问题似乎在于 POS Tagger 的第一个值为 Num。请记住,如果短语以其他方式开头,它可能会起作用。
  • @TiagoDuque 我只得到1+ years2 years(?:year|month)s?years?|months? 是等价的。 1X,而不是 num,这就是它不匹配的原因。
  • 我猜它与“较低”有关。现在你纠正了它,它在这里工作。
猜你喜欢
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
相关资源
最近更新 更多