我正在尝试将输入与我创建的名称数组进行匹配。这是代码:
>>> from fuzzywuzzy import process
>>> names = ["Adam Gilchrist","Adam Barbar","Adam lobiof","Jaffer Wilson","Janet Wilson","Jane Cold"]
>>> process.extract('adamgilchrist',names)
[('Adam Gilchrist', 84), ('Adam lobiof', 50), ('Jane Cold', 50), ('Adam Barbar', 40), ('Janet Wilson', 30)]
我得到的只是一个名字和信心的阵列。
我想将输出显示为json,如下所示:
{
"results": [
{
"name": "Adam Gilchrist",
"confidence": 84
},
{
"name": "Adam lobiof",
"confidence": 50
},
{
"name": "Jane Cold",
"confidence": 50
},
{
"name": "Adam Barbar",
"confidence": 40
},
{
"name": "Janet Wilson",
"confidence": 30
}
]
}
我在windows 10 sysytem上使用python 2.7
答案 0 :(得分:0)
您可以将元组解包与列表推导结合使用:
...
result = process.extract('adamgilchrist',names)
result = [{"name": name, "confidence": confidence} for name, confidence in result]
导致
[{'confidence': 84, 'name': 'Adam Gilchrist'}, {'confidence': 50, 'name': 'Adam lobiof'}, {'confidence': 50, 'name': 'Jane Cold'}, {'confidence': 40, 'name': 'Adam Barbar'}, {'confidence': 30, 'name': 'Janet Wilson'}]
您可以通过微调来达到最终结果(如有必要):
{'result': results}
然后
{'result': [
{'confidence': 84, 'name': 'Adam Gilchrist'},
{'confidence': 50, 'name': 'Adam lobiof'},
{'confidence': 50, 'name': 'Jane Cold'},
{'confidence': 40, 'name': 'Adam Barbar'},
{'confidence': 30, 'name': 'Janet Wilson'}]
}