鉴于 Python 3.5 中的以下解析历史,我正在尝试创建一个带括号的树:
parse = [('S', 0), ('NP', 1), ('Det', 0), 'scan', ('N', 0), 'scan', ('VP', 1), ('V', 4), 'scan', ('NP', 2), ('NP', 0), ('PN', 1), 'scan', ('NP', 1), ('Det', 0), 'scan', ('N', 3), 'scan']
句子是:“那个男人给玛丽看狗”
使用的语法是:
grammar = {'S': [['NP', 'VP']],
'NP': [['PN'], ['Det', 'N'], ['NP', 'NP']],
'VP': [['V'], ['V', 'NP']],
'PN': [['John'], ['Mary'], ['Bill']],
'Det': [['the'], ['a']],
'N': [['man'], ['woman'], ['drill sergeant'], ['dog']],
'V': [['slept'], ['cried'], ['assaulted'],
['devoured'], ['showed']]}
列表中每个元组的格式是元组中的第一项是包含可能规则列表的字典中的键,元组中的第二项是返回给定语法的列表中规则的索引[键][index] 每当 'scan' 出现时,这意味着
输出需要是:
(S(NP(Det the)(N man))(VP (V showed)(NP (NP(PN Mary))(NP(Det the)(N dog)))))
到目前为止我得到的最好的输出是:
(S
NP)
VP)
(NP
Det)
N)
(Det
the)
(N
man)
(VP
V)
NP)
(V
showed)
(NP
NP)
NP)
(NP
PN)
(PN
Mary)
(NP
Det)
N)
(Det
the)
(N
dog)
给定以下代码:
for item in parse:
if item != 'scan':
print("(" + item[0])
for rule in grammar[item[0]][item[1]]:
print(rule + ")")
请帮忙!
谢谢