我在一个NLP项目中工作,我必须使用spacy和spacy Matcher来提取所有命名实体,它们是nsubj (主题)和与之相关的动词:我的NE nsubj的管理者动词。示例:
Georges and his friends live in Mexico City
"Hello !", says Mary我需要提取第一句中的"Georges“和"live”,以及第二句中的"Mary“和”and“,但我不知道在我的命名实体和与其相关的动词之间会有多少个单词。所以我决定更多地探索spacy Matcher。所以我正在努力在Matcher上写一个模式来提取我的2个单词。当NE subj在动词之前时,我得到了很好的结果,但我不知道如何编写模式来匹配与之相关的单词后面的NE subj。根据指南,我也可以用“常规间隔”来完成这项任务,但我不知道该怎么做。Matcher的问题是我不能管理NE和动词之间的依赖类型,也不能抓取好的动词。我是spacy的新手,我一直与NLTK或Jieba (中文)合作。我甚至不知道如何在句子中使用空格标记文本。但我选择将整个文本分成几个句子,以避免两个句子之间的不匹配。以下是我的代码
import spacy
from nltk import sent_tokenize
from spacy.matcher import Matcher
nlp = spacy.load('fr_core_news_md')
matcher = Matcher(nlp.vocab)
def get_entities_verbs():
try:
# subjet before verb
pattern_subj_verb = [{'ENT_TYPE': 'PER', 'DEP': 'nsubj'}, {"POS": {'NOT_IN':['VERB']}, "DEP": {'NOT_IN':['nsubj']}, 'OP':'*'}, {'POS':'VERB'}]
# subjet after verb
# this pattern is not good
matcher.add('ent-verb', [pattern_subj_verb])
for sent in sent_tokenize(open('Le_Ventre_de_Paris-short.txt').read()):
sent = nlp(sent)
matches = matcher(sent)
for match_id, start, end in matches:
span = sent[start:end]
print(span)
except Exception as error:
print(error)
def main():
get_entities_verbs()
if __name__ == '__main__':
main()即使是法语,我也可以向你保证我得到了很好的结果
Florent regardait
Lacaille reparut
Florent baissait
Claude regardait
Florent resta
Florent, soulagé
Claude s’était arrêté
Claude en riait
Saget est matinale, dit
Florent allait
Murillo peignait
Florent accablé
Claude entra
Claude l’appelait
Florent regardait
Florent but son verre de punch ; il le sentit
Alexandre, dit
Florent levait
Claude était ravi
Claude et Florent revinrent
Claude, les mains dans les poches, sifflant我有一些错误的结果,但90%是好的。我只需要抓取每一行的第一个和最后一个单词,就可以让我的夫妇NE/动词。所以我的问题是。当NE与与Matcher相关的动词为subj时,如何提取NE,或者如何使用spacy (而不是Matcher)来提取NE?要考虑的因素有很多。你有没有办法在100%不可能的情况下获得最好的结果。我需要一个匹配动词调控器+ NER subj的模式:
pattern = [
{
"RIGHT_ID": "person",
"RIGHT_ATTRS": {"ENT_TYPE": "PERSON", "DEP": "nsubj"},
},
{
"LEFT_ID": "person",
"REL_OP": "<",
"RIGHT_ID": "verb",
"RIGHT_ATTRS": {"POS": "VERB"},
}
]此模式的所有功劳归功于polm23
发布于 2021-04-26 13:05:54
这是一个完美的依赖匹配器用例。如果在运行它之前将实体合并为单个令牌,也会使事情变得更容易。这段代码应该能做你需要的事情:
import spacy
from spacy.matcher import DependencyMatcher
nlp = spacy.load("en_core_web_sm")
# merge entities to simplify this
nlp.add_pipe("merge_entities")
pattern = [
{
"RIGHT_ID": "person",
"RIGHT_ATTRS": {"ENT_TYPE": "PERSON", "DEP": "nsubj"},
},
{
"LEFT_ID": "person",
"REL_OP": "<",
"RIGHT_ID": "verb",
"RIGHT_ATTRS": {"POS": "VERB"},
}
]
matcher = DependencyMatcher(nlp.vocab)
matcher.add("PERVERB", [pattern])
texts = [
"John Smith and some other guy live there",
'"Hello!", says Mary.',
]
for text in texts:
doc = nlp(text)
matches = matcher(doc)
for match in matches:
match_id, (start, end) = match
# note order here is defined by the pattern, so the nsubj will be first
print(doc[start], "::", doc[end])
print()https://stackoverflow.com/questions/67259823
复制相似问题