Как превратить массив из nltk.tree в другое дерево? - PullRequest
0 голосов
/ 28 августа 2018

У меня есть список, составленный nltk.tree.Tree

>>>question = 'When did Beyonce start becoming popular?'
>>>questionSpacy = spacy_nlp(question)
>>>print(questionSpacy)
[Tree('start_VB_ROOT', ['When_WRB_advmod', 'did_VBD_aux', 'Beyonce_NNP_nsubj', Tree('becoming_VBG_xcomp', ['popular_JJ_acomp']), '?_._punct'])]

Цель состоит в том, чтобы сделать другое дерево. Я знаю, что это глупо, но в противном случае я не знаю, как узнать, содержится ли дерево, представляющее предложение, в другом, представляющем другое предложение.

Я предпринял попытку, но она не удалась. Я думаю, что я не принял во внимание каждый случай. Иногда родительский узел должен быть array[0].label(), а иногда array[0].

from nltk import Tree

class WordTree:
    def __init__(self, array, parent = None):
        #print("son :",array[0][i])
        self.parent = []
        self.children = [] # if parenthesis then it has son after "," analyse : include all elements until the next parenthesi
        self.data = array
        #print(array[0])
        for son in array[0]:
            print(type(son),son)
            if type(son) is Tree:
                print("sub tree creation")
                self.children.append(son.label())
                print("son:",son)
                t = WordTree(son,son.label()) # should I verify if parent is empty ?
                print("end of sub tree creation")
            elif type(son) is str:
                print("son creation")
                self.children.append(son)
            else:
                print("issue?")
                break # prolbem ?

И когда я запускаю t = WordTree(treeQuestion, treeQuestion[0].label()), я получаю следующий вывод:

<class 'str'> When_WRB_advmod
son creation
<class 'str'> did_VBD_aux
son creation
<class 'str'> Beyonce_NNP_nsubj
son creation
<class 'nltk.tree.Tree'> (becoming_VBG_xcomp popular_JJ_acomp)
sub tree creation
son: (becoming_VBG_xcomp popular_JJ_acomp)
<class 'str'> p
son creation
<class 'str'> o
son creation
<class 'str'> p
son creation
<class 'str'> u
son creation
<class 'str'> l
son creation
<class 'str'> a
son creation
<class 'str'> r
son creation
<class 'str'> _
son creation
<class 'str'> J
son creation
<class 'str'> J
son creation
<class 'str'> _
son creation
<class 'str'> a
son creation
<class 'str'> c
son creation
<class 'str'> o
son creation
<class 'str'> m
son creation
<class 'str'> p
son creation
end of sub tree creation
<class 'str'> ?_._punct
son creation

Как видите, в ('becoming_VBG_xcomp', ['popular_JJ_acomp']) он использует буквы сына, popular_JJ_acomp, чтобы создать нескольких сыновей, а не его имя, чтобы сделать одного сына. Это ошибка конечно. Поэтому как превратить массив из nltk.tree в другое дерево?

1 Ответ

0 голосов
/ 29 августа 2018

Я думаю, что нашел что-то, что преобразует массив, созданный nltk.tree, в дерево, созданное с помощью Python, но я пока не смог его обобщить.

from anytree import Node, RenderTree

class WordTree:
    '''Tree for spaCy dependency parsing array'''
    def __init__(self, array, parent = None):
        """
        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 = array

        for element in array[0]:
            print(type(element),element)
            # we check if we got a subtree
            if type(element) is Tree:
                print("sub tree creation")
                self.children.append(element.label())
                print("son:",element)
                t = WordTree([element],element.label())
                print("end of sub tree creation")
            # else if we have a string we create a son
            elif type(element) is str:
                print("son creation")
                self.children.append(element)
            # in other case we have a problem
            else:
                print("issue?")
                break 

Действительно, это хорошо работает со следующим примером:

[Tree('start_VB_ROOT', ['When_WRB_advmod', 'did_VBD_aux', 'Beyonce_NNP_nsubj', Tree('becoming_VBG_xcomp', ['popular_JJ_acomp']), '?_._punct'])]

Даёт:

<class 'str'> When_WRB_advmod
son creation
<class 'str'> did_VBD_aux
son creation
<class 'str'> Beyonce_NNP_nsubj
son creation
<class 'nltk.tree.Tree'> (becoming_VBG_xcomp popular_JJ_acomp)
sub tree creation
son: (becoming_VBG_xcomp popular_JJ_acomp)
<class 'str'> popular_JJ_acomp
son creation
end of sub tree creation
<class 'str'> ?_._punct
son creation

Но у меня нет выводов при попытке:

for i,sent in enumerate(sentences):
    i = WordTree(sentences, sentences[0].label())
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...