Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Matcher正在返回一些重复项_Python_Python 3.x_Nlp_Spacy_Matcher - Fatal编程技术网

Python Matcher正在返回一些重复项

Python Matcher正在返回一些重复项,python,python-3.x,nlp,spacy,matcher,Python,Python 3.x,Nlp,Spacy,Matcher,我希望输出为[“良好的客户服务”,“良好的氛围”],但我得到的是[“良好的客户”,“良好的客户服务”,“良好的氛围”],因为模式也与良好的客户相匹配,但这个短语没有任何意义。我怎样才能删除这些重复项 import spacy from spacy.matcher import Matcher nlp = spacy.load("en_core_web_sm") doc = nlp("good customer service and great ambience") matcher = Matc

我希望输出为
[“良好的客户服务”,“良好的氛围”]
,但我得到的是
[“良好的客户”,“良好的客户服务”,“良好的氛围”]
,因为模式也与良好的客户相匹配,但这个短语没有任何意义。我怎样才能删除这些重复项

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])


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

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)最大的项。

Spacy有一个内置函数来实现这一点。检查:

文件说:

当跨距重叠时,首选(第一个)最长跨距而不是较短跨距

例如:

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

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