Python >> Tutoriel Python >  >> Python

Comment obtenir toutes les phrases nominales dans Spacy

Veuillez voir le code commenté ci-dessous pour combiner récursivement les noms. Code inspiré des Spacy Docs ici

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)

Pour chaque morceau de nom, vous pouvez également obtenir le sous-arbre en dessous. Spacy propose deux façons d'y accéder :left_edge et right edge attributs et les subtree attribut, qui renvoie un Token itérateur plutôt qu'un span.Combining noun_chunks et leur sous-arborescence entraîne des doublons qui peuvent être supprimés ultérieurement.

Voici un exemple utilisant le left_edge et right edge attributs

{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'}