【问题标题】:How to avoid double-extracting of overlapping patterns in SpaCy with Matcher?如何避免在 SpaCy 中使用 Matcher 双重提取重叠模式?
【发布时间】:2020-08-07 12:37:19
【问题描述】:

我需要通过 python Spacy Matcher 从 2 个列表中提取项目组合。问题如下: 让我们有 2 个列表:

colors=['red','bright red','black','brown','dark brown']
animals=['fox','bear','hare','squirrel','wolf']

我通过以下代码匹配序列:

first_color=[]
last_color=[]
only_first_color=[]
for color in colors:
    if ' ' in color:
        first_color.append(color.split(' ')[0])
        last_color.append(color.split(' ')[1])
    else:
        only_first_color.append(color)
matcher = Matcher(nlp.vocab)

pattern1 = [{"TEXT": {"IN": only_first_color}},{"TEXT":{"IN": animals}}]
pattern2 = [{"TEXT": {"IN": first_color}},{"TEXT": {"IN": last_color}},{"TEXT":{"IN": animals}}]

matcher.add("ANIMALS", None, pattern1,pattern2)

doc = nlp('bright red fox met black wolf')

matches = matcher(doc)

for match_id, start, end in matches:
    string_id = nlp.vocab.strings[match_id]  # Get string representation
    span = doc[start:end]  # The matched span
    print(start, end, span.text)

它给出了输出:

0 3 bright red fox
1 3 red fox
4 6 black wolf

我怎样才能只提取'bright red fox'和'black wolf'?我应该更改模式规则还是对匹配进行后处理?

任何想法不胜感激!

【问题讨论】:

  • 什么是title
  • 对不起,它来自旧代码版本。现已编辑。

标签: python nlp spacy matcher


【解决方案1】:

您可以使用spacy.util.filter_spans:

过滤一系列Span 对象并删除重复或重叠。 用于创建命名实体(其中一个标记只能是一部分 一个实体)或与Retokenizer.merge 合并跨度时。什么时候 跨度重叠,(第一个)最长的跨度优于较短的跨度 跨度。

Python 代码:

matches = matcher(doc)
spans = [doc[start:end] for _, start, end in matches]
for span in spacy.util.filter_spans(spans):
    print(span.start, span.end, span.text)

输出:

0 3 bright red fox
4 6 black wolf

【讨论】:

  • 非常感谢!这真的是一个优雅的解决方案。我是 spacy 的新手,我不知道 spacy.util.filter_spans 的可能性。它对我很有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-20
  • 1970-01-01
相关资源
最近更新 更多