我正在尝试解析一棵树,但出现以下错误。类型错误:元组索引必须是整数,而不是 str?
def parseExpression(expression):
nodeMap = dict()
counter = 1
node = ""
retExp =""
for char in expression:
if char == '(' or char == ')' :
if (len(node) > 0):
nodeMap[str(counter)] = node;
retExp += str(counter)
counter +=1
retExp += char
node =""
elif char == ' ': continue
else :
node += char
return retExp,nodeMap
def printTree(tree, node, nodeMap):
if node not in tree:
return
print ('%s -> %s' % (nodeMap[node], ' '.join(nodeMap[child] for child in tree[node])) )
for child in tree[node]:
printTree(tree, child, nodeMap)
expression = " ( Root( SQ ( VBZ ) ( NP ( DT ) ( NN ) ) ( VP ( VB ) ( NP ( NN ) ) ) ))"
expression, nodeMap = parseExpression(expression)
tree = parseExpression(expression)
printTree(tree, tree[''][0], nodeMap)
输出 :
Root -> SQ
SQ -> VBZ NP VP
NP -> DT NN
VP -> VB NP
NP -> NN
有人可以帮助调试这个程序,任何帮助表示感谢,谢谢。
Traceback (most recent call last):
File "C:/Python33/refd.py", line 29, in <module>
printTree(tree, tree[''][0], nodeMap)
TypeError: tuple indices must be integers, not str