python解析树_如何使用python中的stanford解析器获取树的叶子?
下面是一個構建樹然后遞歸地構建葉子列表的示例。示例文本取自the online standford parser。在# class for tree nodes
class Node:
def __init__(self,start):
self.start = start
self.children = []
self.text = ''
# make a tree
def make_tree(s):
stack = []
nodes = []
cur = None
root = None
for i, c in enumerate(s):
if c == '(':
cur = Node(i)
if stack:
stack[-1].children.append(cur)
stack.append(cur)
if root is None:
root = cur
elif c == ')' and stack:
topnode = stack.pop()
text = s[topnode.start + 1: i]
topnode.text = text
return root
# list of leaves
def list_of_leaves(node):
result = []
for child in node.children:
result.extend(list_of_leaves(child))
if not result:
return [node]
return result
s = """(ROOT
(SQ (VBD Did)
(NP (NNP Matt))
(VP (VB win)
(NP (DT the) (NNS men) (NN slalom)))
(. ?)))"""
root = make_tree(s)
for node in list_of_leaves(root):
print node.text
總結
以上是生活随笔為你收集整理的python解析树_如何使用python中的stanford解析器获取树的叶子?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 宽屏企业网站源码中英php_宽屏版大气企
- 下一篇: python中转义字符怎么用_pytho