Por ejemplo tengo una oración que puedo analizar como un árbol con spaCy
y nltk
.
When did Beyonce start becoming popular?
es el array treeQuestion[0]
:
[Tree('start_VB_ROOT', ['When_WRB_advmod', 'did_VBD_aux',
'Beyonce_NNP_nsubj', Tree('becoming_VBG_xcomp', ['popular_JJ_acomp']),
'?_._punct'])]
Lo hice con el siguiente código:
>>>questionSpacy = spacy_nlp(question)
>>>treeQuestion = nltk_spacy_tree(questionSpacy)
>>>print(treeQuestion)
When did Beyonce start becoming popular?
[to_nltk_tree(sent.root).pretty_print() for sent in en_nlp(predicted.iloc[0,3]).sents]
>>>treeQuestion = nltk_spacy_tree(questionSpacy)
>>>print(treeQuestion)
[Tree('start_VB_ROOT', ['When_WRB_advmod', 'did_VBD_aux', 'Beyonce_NNP_nsubj', Tree('becoming_VBG_xcomp', ['popular_JJ_acomp']), '?_._punct'])]
start
__________|___________
| | | | becoming
| | | | |
When did Beyonce ? popular
Y me gustaría saber si treeQuestion
está contenido en el siguiente árbol y en que medida se ha mostrado, por ejemplo la siguiente:
--- 1 ---
born and raised in houston, texas, she performed in various singing and dancing competitions as a child, and rose to fame in the late 1990s as lead singer of r&b girl-group destiny's child.
[Tree('performed_VBD_ROOT', [Tree('born_VBN_advcl', ['and_CC_cc', Tree('raised_VBN_conj', [Tree('in_IN_prep', [Tree('houston_NN_pobj', [',_,_punct'])]), 'texas_NN_npadvmod'])]), ',_,_punct', 'she_PRP_nsubj', Tree('in_IN_prep', [Tree('competitions_NNS_pobj', ['various_JJ_amod', Tree('singing_NN_nmod', ['and_CC_cc', 'dancing_NN_conj'])])]), Tree('as_IN_prep', [Tree('child_NN_pobj', ['a_DT_det'])]), ',_,_punct', 'and_CC_cc', Tree('rose_VBD_conj', [Tree('to_IN_prep', ['fame_NN_pobj']), Tree('in_IN_prep', [Tree('1990s_NNS_pobj', ['the_DT_det', 'late_JJ_amod'])]), Tree('as_IN_prep', [Tree('singer_NN_pobj', ['lead_JJ_compound', Tree('of_IN_prep', ['r&b_NN_punct', Tree('child_NN_pobj', [Tree('destiny_NN_poss', [Tree('group_NN_compound', ['girl_NN_compound', '-_HYPH_punct']), "'s_POS_case"])])])])])]), '._._punct'])]
performed
________________________________________________________|__________________________________________________
| | | | | | | | rose
| | | | | | | | ___________________|_________
| | | | | | | | | | as
| | | | | | | | | | |
| | | | | | | | | | singer
| | | | | | | | | | _________|_____
| | | | | born | | | | | of
| | | | | ____|_____ | | | | | __________|_____
| | | | | | raised in | | | | | child
| | | | | | _____|_______ | | | | | | |
| | | | | | | in competitions as | in | | destiny
| | | | | | | | _________|__________ | | | | | ___________|______
| | | | | | | houston | singing child to 1990s | | | group
| | | | | | | | | __________|_______ | | ____|____ | | | ______|____
, she , and . and texas , various and dancing a fame the late lead r&b 's girl
De hecho, como uno puede ver podemos encontrar rose to fame
que es muy similar a start becoming popular
. En cuanto a la mitad (3/6) del árbol está aquí podemos decir que 50% se ha mostrado.
Un contraejemplo, uno con un puntaje malo, hubiera sido el siguiente :
--- 0 ---
beyoncé giselle knowles-carter (/biːˈjɒnseɪ/ bee-yon-say) (born september 4, 1981) is an american singer, songwriter, record producer and actress.
[Tree('is_VBZ_ROOT', [Tree('carter_NN_nsubj', [Tree('giselle_NN_compound', ['beyoncé_NN_amod']), 'knowles_NNS_compound', '-_HYPH_punct', Tree('say_NN_parataxis', ['(_-LRB-_punct', '/biːˈjɒnseɪ/_-LRB-_amod', Tree('yon_NN_compound', ['bee_NN_compound', '-_HYPH_punct']), '-_HYPH_punct']), ')_-RRB-_punct', '(_-LRB-_punct', Tree('born_VBN_acl', [Tree('september_NN_npadvmod', ['4_CD_nummod', ',_,_punct', '1981_CD_nummod'])]), ')_-RRB-_punct']), Tree('singer_NN_attr', ['an_DT_det', 'american_JJ_amod', ',_,_punct', Tree('songwriter_NN_conj', [',_,_punct', Tree('producer_NN_conj', ['record_NN_compound', 'and_CC_cc', 'actress_NN_conj'])])]), '._._punct'])]
is
___________________________________________________________|________________________________________________
| carter singer
| ______________________________|_________________________________________ _________________|_______________
| | | | | | | say born | | | songwriter
| | | | | | | __________________|_______ | | | | _______________|_________
| | | | | | giselle | | | yon september | | | | producer
| | | | | | | | | | ___|___ ______|______ | | | | __________________|________
. knowles - ) ( ) beyoncé ( /biːˈjɒnseɪ/ - bee - 4 , 1981 an american , , record and actress
Actualización 31/08
Encontré una forma de saber cuando un objeto está contenido en otro. Dejo el botín abierto para la persona que pueda decirme cuando un árbol es similar a otro, especialmente a través de sinónimos o. Por ejemplo:
rose to fame
forstart becoming popular
start being popular
forstart becoming popular
Transforma una lista en un árbol.
class WordTree:
'''Tree for spaCy dependency parsing array'''
def __init__(self, tree, is_subtree=False):
"""
Construct a new 'WordTree' object.
:param tree: The array contening the dependency
:param parent: The parent of the tree if exists
:return: returns nothing
"""
self.parent = []
self.children = []
self.data = tree.label().split('_')[0] # the first element of the tree # We are going to add the synonyms as well.
for subtree in tree:
if type(subtree) == Tree:
# Iterate through the depth of the subtree.
t = WordTree(subtree, True)
t.parent=tree.label().split('_')[0]
elif type(subtree) == str:
surface_form = subtree.split('_')[0]
self.children.append(surface_form)
Probar si un árbol está contenido en otro
def isSubtree(T,S):
if S is None:
return True
if T is None:
return False
if areIdentical(T, S):
return True
return any(isSubtree(c, S) for c in T.children)
def areIdentical(root1, root2):
'''
function to say if two roots are identical
'''
# Base Case
if root1 is None and root2 is None:
return True
if root1 is None or root2 is None:
return False
# Check if the data of both roots their and children are the same
return (root1.data == root2.data and
((areIdentical(child1 , child2))
for child1, child2 in zip(root1.children, root2.children)))
Ejemplo
# first tree creation
text = "start becoming popular"
textSpacy = spacy_nlp(text)
treeText = nltk_spacy_tree(textSpacy)
t = WordTree(treeText[0])
# second tree creation
question = "When did Beyonce start becoming popular?"
questionSpacy = spacy_nlp(question)
treeQuestion = nltk_spacy_tree(questionSpacy)
q = WordTree(treeQuestion[0])
# tree comparison
isSubtree(t,q)
Aquí probamos dos árboles de dos oraciones donde una es una subparte de la otra. Tenemos entonces True
. Puede ser interesante encontrar una manera de decir cuando uno está parcialmente contenido en el otro.
.similarity()
en spaCy. Intentaré comparar dos textos. Sin embargo, hay uno que es muy largo y el otro que es relativamente pequeño, la preguntatreeQuestion
.