Extract parent and child node from python tree representation

假如想象 提交于 2019-12-08 15:05:17

问题


[Tree('ROOT', [Tree('S', [Tree('INTJ', [Tree('UH', ['Hello'])]), Tree(',', [',']), Tree('NP', [Tree('PRP$', ['My']), Tree('NN', ['name'])]), Tree('VP', [Tree('VBZ', ['is']), Tree('ADJP', [Tree('JJ', ['Melroy'])])]), Tree('.', ['.'])])]), Tree('ROOT', [Tree('SBARQ', [Tree('WHNP', [Tree('WP', ['What'])]), Tree('SQ', [Tree('VBZ', ['is']), Tree('NP', [Tree('PRP$', ['your']), Tree('NN', ['name'])])]), Tree('.', ['?'])])])]

I have many of these strings available in Python, which are actually tree representations. I want to extract the parent and child node for every word, e.g. for 'Hello' I want (INTJ, UH), and for 'My' it is (NP, PRP$).

This is the outcome I want:

(INTJ, UH) , (NP, PRP$), (NP, NN) , (VP, VBZ) , (VP , VPZ) , (ADJP, JJ) , (WHNP, WP), (SQ, VBZ), (NP, PRP$), (NP, NN)

How can I do that?


回答1:


Your string is obviously the representation of a list of Tree objects. It would be much better if you had access to, or could reconstruct in some other way, that list – if not, the most straightforward way to create a data structure you can work with is eval() (with all the usual caveats about calling eval() on user-supplied data).

Since you don't say anything about your Tree class, I'll write a simple one that suffices for the purposes of this question:

class Tree:

    def __init__(self, name, branches):
        self.name = name
        self.branches = branches

Now we can recreate your data structure:

data = eval("""[Tree('ROOT', [Tree('S', [Tree('INTJ', [Tree('UH', ['Hello'])]), Tree(',', [',']), Tree('NP', [Tree('PRP$', ['My']), Tree('NN', ['name'])]), Tree('VP', [Tree('VBZ', ['is']), Tree('ADJP', [Tree('JJ', ['Melroy'])])]), Tree('.', ['.'])])]), Tree('ROOT', [Tree('SBARQ', [Tree('WHNP', [Tree('WP', ['What'])]), Tree('SQ', [Tree('VBZ', ['is']), Tree('NP', [Tree('PRP$', ['your']), Tree('NN', ['name'])])]), Tree('.', ['?'])])])]""")

Once we have that, we can write a function that produces the list of 2-tuples you want:

def tails(items, path=()):
    for item in items:
        if isinstance(item, Tree):
            if item.name in {".", ","}:  # ignore punctuation
                continue
            for result in tails(item.branches, path + (item.name,)):
                yield result
        else:
            yield path[-2:]

This function descends recursively into the tree, yielding the last two Tree names each time it hits an appropriate leaf node.

Example use:

>>> list(tails(data))
[('INTJ', 'UH'), ('NP', 'PRP$'), ('NP', 'NN'), ('VP', 'VBZ'), ('ADJP', 'JJ'), ('WHNP', 'WP'), ('SQ', 'VBZ'), ('NP', 'PRP$'), ('NP', 'NN')]


来源:https://stackoverflow.com/questions/29247241/extract-parent-and-child-node-from-python-tree-representation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!