如何在Spacy中获取所有名词短语

编程入门 行业动态 更新时间:2024-10-25 04:24:43
本文介绍了如何在Spacy中获取所有名词短语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是Spacy的新手,我想从句子中提取所有"名词短语.我想知道我该怎么做.我有以下代码:

I am new to Spacy and I would like to extract "all" the noun phrases from a sentence. I'm wondering how I can do it. I have the following code:

import spacy nlp = spacy.load("en") file = open("E:/test.txt", "r") doc = nlp(file.read()) for np in doc.noun_chunks: print(np.text)

但是它仅返回基本名词短语,即其中不包含任何其他NP的短语.也就是说,对于以下短语,我得到以下结果:

But it returns only the base noun phrases, that is, phrases which don't have any other NP in them. That is, for the following phrase, I get the result below:

短语:We try to explicitly describe the geometry of the edges of the images.

结果:We, the geometry, the edges, the images.

预期结果:We, the geometry, the edges, the images, the geometry of the edges of the images, the edges of the images.

如何获取所有名词短语,包括嵌套短语?

How can I get all the noun phrases, including nested phrases?

推荐答案

请参阅下面的注释代码以递归方式组合名词.受此处的Spacy文档

Please see commented code below to recursively combine the nouns. Code inspired by the Spacy Docs here

import spacy nlp = spacy.load("en") doc = nlp("We try to explicitly describe the geometry of the edges of the images.") for np in doc.noun_chunks: # use np instead of np.text print(np) print() # code to recursively combine nouns # 'We' is actually a pronoun but included in your question # hence the token.pos_ == "PRON" part in the last if statement # suggest you extract PRON separately like the noun-chunks above index = 0 nounIndices = [] for token in doc: # print(token.text, token.pos_, token.dep_, token.head.text) if token.pos_ == 'NOUN': nounIndices.append(index) index = index + 1 print(nounIndices) for idxValue in nounIndices: doc = nlp("We try to explicitly describe the geometry of the edges of the images.") span = doc[doc[idxValue].left_edge.i : doc[idxValue].right_edge.i+1] span.merge() for token in doc: if token.dep_ == 'dobj' or token.dep_ == 'pobj' or token.pos_ == "PRON": print(token.text)

更多推荐

如何在Spacy中获取所有名词短语

本文发布于:2023-10-23 01:55:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519395.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:短语   名词   如何在   Spacy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!