gpt4 book ai didi

python - SimpleJson 处理相同的命名实体

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:59 27 4
gpt4 key购买 nike

我在 App Engine 中使用 Alchemy API,因此我使用 simplejson 库来解析响应。问题是响应中的条目具有 sme 名称

 {
"status": "OK",
"usage": "By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html",
"url": "",
"language": "english",
"entities": [
{
"type": "Person",
"relevance": "0.33",
"count": "1",
"text": "Michael Jordan",
"disambiguated": {
"name": "Michael Jordan",
"subType": "Athlete",
"subType": "AwardWinner",
"subType": "BasketballPlayer",
"subType": "HallOfFameInductee",
"subType": "OlympicAthlete",
"subType": "SportsLeagueAwardWinner",
"subType": "FilmActor",
"subType": "TVActor",
"dbpedia": "http://dbpedia.org/resource/Michael_Jordan",
"freebase": "http://rdf.freebase.com/ns/guid.9202a8c04000641f8000000000029161",
"umbel": "http://umbel.org/umbel/ne/wikipedia/Michael_Jordan",
"opencyc": "http://sw.opencyc.org/concept/Mx4rvViVq5wpEbGdrcN5Y29ycA",
"yago": "http://mpii.de/yago/resource/Michael_Jordan"
}
}
]
}

所以问题是重复了“subType”,所以加载返回的字典只是“TVActor”而不是列表。有什么办法可以解决这个问题吗?

最佳答案

rfc 4627定义 application/json 说:

An object is an unordered collection of zero or more name/value pairs

和:

The names within an object SHOULD be unique.

这意味着 AlchemyAPI 不应在同一对象内返回多个 “subType” 名称并声称它是 JSON。

您可以尝试请求相同的 XML 格式 (outputMode=xml) 以避免结果中的歧义或将重复的键值转换为列表:

import simplejson as json
from collections import defaultdict

def multidict(ordered_pairs):
"""Convert duplicate keys values to lists."""
# read all values into lists
d = defaultdict(list)
for k, v in ordered_pairs:
d[k].append(v)

# unpack lists that have only 1 item
for k, v in d.items():
if len(v) == 1:
d[k] = v[0]
return dict(d)

print json.JSONDecoder(object_pairs_hook=multidict).decode(text)

例子

text = """{
"type": "Person",
"subType": "Athlete",
"subType": "AwardWinner"
}"""

输出

{u'subType': [u'Athlete', u'AwardWinner'], u'type': u'Person'}

关于python - SimpleJson 处理相同的命名实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7825261/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com