我使用libpostal地址決議庫作為.exe檔案。我有一個腳本來讀取終端的輸出。輸出將是一個string與dict格式像下面,

這是地址字串
"531A UPPER CROSS STREETSINGAPORE HONG LIM COMPLEX 051531 S"
libpostal 終端輸出是
'{\n "house_number": "531a",\n "road": "upper cross streetsingapore",\n "city": "hong",\n "house": "lim complex",\n "house_number": "051531 s"\n}'
我需要Dict從這個字串創建一個,如果有重復的鍵,然后將這些值附加到同一個鍵中。
預期輸出 Dict
{
"house_number": "531a 051531 s",
"road": "upper cross streetsingapore",
"city": "hong",
"house": "lim complex",
}
幫助將不勝感激
uj5u.com熱心網友回復:
您可以使用json.JSONDecoder將 dict 文字解碼為元組串列,用于dict.setdefault將值組合到串列中,最后將所有專案連接到 dicts 值中:
string = '{\n "house_number": "531a",\n "road": "upper cross streetsingapore",\n "city": "hong",\n "house": "lim complex",\n "house_number": "051531 s"\n}'
from json import JSONDecoder
decoder = JSONDecoder(object_pairs_hook=lambda x: x).decode(string)
out = {}
for tpl in decoder:
out.setdefault(tpl[0],[]).append(tpl[1])
out = {k:' '.join(v) for k,v in out.items()}
輸出:
{'house_number': '531a 051531 s',
'road': 'upper cross streetsingapore',
'city': 'hong',
'house': 'lim complex'}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/379922.html
