Soy nuevo en Spacy y me gustaría extraer "todos" los sintagmas nominales de una oración. Me pregunto cómo puedo hacerlo. Tengo el siguiente código:
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) Pero solo devuelve las frases nominales base, es decir, frases que no tienen ningún otro NP en ellas. Es decir, para la siguiente frase, obtengo el resultado a continuación:
Frase: We try to explicitly describe the geometry of the edges of the images.
Resultado: We, the geometry, the edges, the images .
Resultado esperado: We, the geometry, the edges, the images, the geometry of the edges of the images, the edges of the images.
¿Cómo puedo obtener todas las frases nominales, incluidas las frases anidadas?
Consulte el código comentado a continuación para combinar recursivamente los sustantivos. Código inspirado en los Spacy Docs aquí
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)Para cada fragmento de sustantivo, también puede obtener el subárbol debajo de él. Spacy proporciona dos formas de acceder a eso: left_edge de borde izquierdo y right edge y el atributo de subtree , que devuelve un iterador de Token en lugar de un tramo. La combinación noun_chunks y su subárbol conduce a cierta duplicación que se puede eliminar más adelante.
Aquí hay un ejemplo usando los left_edge de borde izquierdo y right 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'}Intente esto para obtener todos los sustantivos de un texto:
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])