【问题标题】:Matcher is returning some duplicates entryMatcher 正在返回一些重复项
【发布时间】:2019-11-12 08:52:36
【问题描述】:

我希望输出为["good customer service","great ambience"],但我得到["good customer","good customer service","great ambience"],因为模式也与好客户匹配,但这个短语没有任何意义。如何删除这些重复项

import spacy
from spacy.matcher import Matcher
nlp = spacy.load("en_core_web_sm")
doc = nlp("good customer service and great ambience")
matcher = Matcher(nlp.vocab)

# Create a pattern matching two tokens: adjective followed by one or more noun
 pattern = [{"POS": 'ADJ'},{"POS": 'NOUN', "OP": '+'}]

matcher.add("ADJ_NOUN_PATTERN", None,pattern)

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

【问题讨论】:

  • 你的意思是说你想让+表现得“贪婪”,只返回最左边索引中最长的匹配?
  • 正确的@WiktorStribiżew,我想要最长的匹配。你能帮我怎么做吗
  • 谁能帮帮我,真的很紧急。
  • 在下面查看我的回答,它对你有用吗?
  • @WiktorStribiżew ,是的,它对我有用,非常感谢您的解决方案。

标签: python python-3.x nlp spacy matcher


【解决方案1】:

Spacy 有一个内置函数可以做到这一点。检查filter_spans:

文档说:

当跨度重叠时,(第一个)最长的跨度优先于较短的跨度。

例子:

doc = nlp("This is a sentence.")
spans = [doc[0:2], doc[0:2], doc[0:4]]
filtered = filter_spans(spans)

【讨论】:

  • 如果你想过滤 spacy.matcher.Matcher() 的结果,请确保使用matcher(doc, as_spans=True),而不仅仅是matcher(doc)
【解决方案2】:

您可以通过根据起始索引对元组进行分组并仅保留具有最大结束索引的元组来对匹配项进行后处理:

from itertools import *

#...

matches = matcher(doc)
results = [max(list(group),key=lambda x: x[2]) for key, group in groupby(matches, lambda prop: prop[1])]    
print("Matches:", [doc[start:end].text for match_id, start, end in results])
# => Matches: ['good customer service', 'great ambience']

groupby(matches, lambda prop: prop[1]) 将在此处按起始索引对匹配进行分组,从而产生[(5488211386492616699, 0, 2), (5488211386492616699, 0, 3)] 和(5488211386492616699, 4, 6)。 max(list(group),key=lambda x: x[2]) 将抓取结束索引(值 #3)最大的项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2018-09-04
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    相关资源
    最近更新 更多