<p>最主要的是识别孩子。我将尝试解释我的代码:</p>
<pre><code>class TreeNode:
def __init__(self, string):
self.im_leaf = string[0] != '('
self.children = []
if not self.im_leaf:
first_space_index = string.index(" ")
self.label = string[1:first_space_index]
string = string[first_space_index + 1 : -1] #rest of the tree
for node in self.split(string):
self.children.append(TreeNode(node))
else:
self.label = string
self.text = self.calculate_text()
def calculate_text(self):
if self.im_leaf:
return self.label + ' '
text = ''
for node in self.children:
text += node.calculate_text()
return text
def split(self, string):
splitted = []
pair_parenthesis = 0
index = 0
for i in range(len(string)):
char = string[i]
if char == '(':
pair_parenthesis += 1
elif char == ')':
pair_parenthesis -= 1
if pair_parenthesis == 0:
new_node = string[index:i+1]
if new_node[0] == ' ':
new_node = new_node[1:]
splitted.append(new_node)
index = i + 1
if len(splitted) == 0:
splitted = [string]
return splitted
</code></pre>
<p>首先,在<code>__init__</code>中,我识别给定字符串是否描述了由第一个字符确定的叶,如果它不是“开括号”(<code>'('</code>),则当前字符串描述了叶,例如<code>"cow"</code>或<code>Where</code>;与“非叶字符串”不同,例如<code>"(NP (DT the) (NN cow))"</code></p>
<p>如果<code>string</code>描述一个叶,那么<code>label = string</code>,否则<code>label</code>是第一个括号(总是在第一个位置)和第一个空白之间的子字符串。另外,在后一种情况下,有必要识别不同的分支,这是通过方法<code>split</code>完成的。然后,递归地识别<code>children</code></p>
<p><code>split</code>方法通过计算开括号和闭括号来识别分支。请注意<code>"(WHADVP (WRB Where)) (VBZ is) (NP (DT the) (NN cow))"</code>中的第一个分支是<code>(WHADVP (WRB Where))</code>,也就是说,当代码中第一次开括号的数量等于闭括号的数量时(这个差异存储在<code>pair_parenthesis</code>)。第二个和第三个分支也是如此。如果分支只有一个子级,例如<code>"(WRB Where)"</code>,则将使用字符串<code>"Where"</code>调用该方法,在这些情况下,该方法返回<code>"[Where]"</code></p>
<p>最后,使用方法<code>calculate_text</code>分配<code>text</code>,该方法基本上通过树进行递归调用来搜索叶子。如果节点是叶,则其标签将添加到<code>text</code></p>
<p>现在进行一些测试:</p>
<pre><code>test_tree = TreeNode('(SBARQ (WHADVP (WRB Where)) (VBZ is) (NP (DT the) (NN cow)))')
print(test_tree.label)
#SBARQ
print(test_tree.text)
#Where is the cow
print(test_tree.children[0].text) #text from the "WHADVP" node
#Where
</code></pre>
<p>如果有什么不清楚的地方,请告诉我</p>