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

11

我是Spacy的新手,希望能够从句子中提取“所有”名词短语。我想知道如何实现。我有以下代码:

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的短语。也就是说,对于以下短语,我得到以下结果:
短语: 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. 如何获取所有名词短语,包括嵌套的短语?
4个回答

12
请查看下面的代码并递归地组合名词。 代码灵感来自于Spacy文档这里
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)

谢谢你的回答。但是你的代码输出是"[0, 5, 8] We geometry edges images We geometry edges images We geometry edges images]",这是什么意思? - user1419243
1
我从上面的代码中得到了以下内容。你是否同时运行了两个循环?你使用的Spacy版本是哪个?[6, 9, 12] 我们 图像的边缘几何形状 我们 几何形状 图像的边缘 我们 几何形状 边缘 图像 - Adnan S
我已经完全复制了你的代码。我正在Windows操作系统上使用Python版本3.6.4和Spacy 2.0.8。 - user1419243
奇怪 - 我正在Linux上运行这个程序,但不应该导致不同的输出。你能否尝试从Spacy(https://spacy.io/models/en#en_core_web_sm)升级语言模型到最新版本?你得到的索引[0,5,8]与我得到的[6,9,12]表明解析树存在差异。你是从第一行开始运行代码吗?第一个输出不应该是“[0,5,8] ....” - Adnan S
很好的解决方案,但我不明白为什么需要这一行代码“span = doc[doc[idxValue].left_edge.i : doc[idxValue].right_edge.i+1]”。你能解释一下吗?谢谢! - ℕʘʘḆḽḘ

3
对于每个名词块,您还可以获取其下方的子树。Spacy提供了两种访问方式:left_edgeright edge属性以及subtree属性,后者返回Token迭代器而不是跨度。将noun_chunks和它们的子树组合起来会导致一些重复,稍后可以删除。以下是一个使用left_edgeright edge属性的示例。
{np.text
  for nc in doc.noun_chunks
  for np in [
    nc, 
    doc[
      nc.root.left_edge.i
      :nc.root.right_edge.i+1]]}                                                                                                                                                                                                                                                                                                                                                                                                                                                 

==>

{'We',
 'the edges',
 'the edges of the images',
 'the geometry',
 'the geometry of the edges of the images',
 'the images'}

2
from spacy.matcher import Matcher
import spacy
nlp = spacy.load("en_core_web_sm")

doc = nlp('Features of the iphone applications include a beautiful design, smart search, automatic labels and optional voice responses.') ## sample text
matcher = Matcher(nlp.vocab)
pattern = [{"POS": "NOUN", "OP": "*"}] ## getting all nouns
matcher.add("NOUN_PATTERN", [pattern])
print(matcher(doc, as_spans=True))

获取文本中的所有名词。使用匹配器和模式可以很好地获得您想要的组合。如果您想要更好的模型,请更改"en_core_web_sm""en_core_web_bm"


2
请尝试以下方法从文本中获取所有名词:

import spacy
nlp = spacy.load("en_core_web_sm")
text = ("We try to explicitly describe the geometry of the edges of the images.")
doc = nlp(text)
print([chunk.text for chunk in doc.noun_chunks])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接