Я хочу знать, когда дерево похоже на часть другого, например, когда
- Когда Бейонсе стала популярной?
частично включено в следующие предложения:
- Она стала популярной в конце 1990-х (случай 1 st )
- Она достигла славы в конце 1990-х (случай 2 и )
Я могу сказать, когда один текст строго включен в другой: я создал класс, который преобразует массив spaCy в дерево, и позже я покажу, как преобразовать текст в spaCy.
class WordTree:
'''Tree for spaCy dependency parsing array'''
def __init__(self, tree, is_subtree=False):
"""
Construct a new 'WordTree' object.
:param array: The array contening the dependency
:param parent: The parent of the array 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)
И я могу сказать, когда одно предложение включается в другую ссылку на следующие функции:
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)))
Действительно, например:
# 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)
Возвращает True
. Поэтому, когда я могу сказать, что дерево частично включено (1 st case) в другой или аналогичный (2 nd case) в другой?