【发布时间】:2016-06-15 14:51:52
【问题描述】:
我有一个 Python 函数,它遍历一个被解析为树的句子,寻找形容词/名词对(例如“好猫”),创建一个此类对的列表,然后返回它。这里是:
def traverse(t):
thelist = list()
try:
t.label()
except AttributeError:
return
else:
if t.label() == 'NP':
for leaf in t.leaves():
thelist.append(str(leaf[0]))
print("The list is ",thelist)
return thelist
else:
for child in t:
traverse(child)
我这样称呼这个函数:
print("traversing the tree returned ",traverse(pos_parser))
我得到的是这样的:
The list is ['good', 'cat']
traversing the tree returned None
所以它在遍历中创建并打印出变量“thelist”,但不返回它(而是返回 None)。为什么??
有人可以帮忙吗?
【问题讨论】:
-
注意:属性错误中的return隐式返回None
-
您是否尝试过在调试器中单步执行?是否遇到 AttributeError 异常?