dictionary - 将 NLTK 树转换为字典数组
问题描述
我想将以下 nltk 树转换为字典数组:
(S
I/PRP
'll/MD
have/VB
(amount 1/CD)
(meal pizza/NN)
with/IN
(ingredient bacon/NN)
and/CC
(amount 2/CD)
(meal hamburgers/NNS)
with/IN
(ingredient cheese/NN))
[{'amount': '1', 'meal': 'pizza', 'ingredient': 'bacon'},
{'amount': '2', 'meal': 'hamburgers', 'ingredient': 'cheese'}]
我创建了下一个代码来获取它:
comanda = [('I', 'PRP'), ("'ll", 'MD'), ('have', 'VB'), ('1', 'CD'), ('pizza', 'NN'), ('with', 'IN'), ('bacon', 'NN'), ('and', 'CC'), ('2', 'CD'), ('hamburgers', 'NNS'), ('with', 'IN'), ('cheese', 'NN')]
def IOB_pedido(menu):
grammar = r"""
meal: {<NN|NNS><IN|NN>}
}<IN>{
ingredient: {<IN>?<NN|NNS>}
}<IN>{
amount: {<CD>}
{<DT>}
"""
result = nltk.RegexpParser(grammar).parse(menu)
iob_tags = tree2conlltags(result)
tree = conlltags2tree(iob_tags)
return tree
output = IOB_pedido(comanda)
def tree_to_dict(tree):
tree_dict = {}
for nodo in tree:
if type(nodo) == tuple:
continue
salida = []
key = nodo.label()
value = nodo[0][0]
tree_dict.update([(key, value)])
salida.append((tree_dict))
return salida
tree_to_dict(output)
但是出于某种原因,只显示了第二部分,这就是我没有得到下一个输出的原因?
[{'amount': '1', 'meal': 'pizza', 'ingredient': 'bacon'},
{'amount': '2', 'meal': 'hamburgers', 'ingredient': 'cheese'}]
解决方案
对不起,我的意思是我得到这样的输出:
[{'amount': '2', 'meal': 'hamburgers', 'ingredient': 'cheese'}]
我想要这样的东西:
[{'amount': '1', 'meal': 'pizza', 'ingredient': 'bacon'},
{'amount': '2', 'meal': 'hamburgers', 'ingredient': 'cheese'}]
我不知道为什么我只将树的第二部分包含在字典列表中。
推荐阅读
- asp.net-mvc - MemoryCache.Count 贵吗?
- google-chrome - 自动除以获得价值的项目数量
- ios - ScreenshotDataForQuality:rect:error:] Appium 与 IOS 14.5
- nextflow - 输出文件(染色体块)在 nextflow 中合并
- android - Android kotlin:如何将图像变成 MultipartBody?
- python - Docker 中的 Python ARM - 安装要求需要很长时间
- c# - 为什么玩家射击时子弹有时不会出现在游戏视图中?
- python - 如何从 matplotlib 返回图例数据
- user-interface - 为什么它显示警告:从不读取字段:`group`?是否有一些选项可以解决此警告?
- django - 通过查询或 ORM 访问 Django 多态模型时的不同结果