gpt4 book ai didi

python - Python 中的尝试/异常(exception) : appropriate for parsing dictionaries?

转载 作者:行者123 更新时间:2023-11-30 22:29:41 25 4
gpt4 key购买 nike

我正在尝试解析包含嵌套列表和字典的字典。我试图检测给定的键是否存在并将其值保存到适当的变量中。下面的代码可以工作,但感觉非常困惑。有没有正确/更好的方法来处理这个问题?

def wit_response(self, message_text=None):
if message_text is not None:
resp = self.client.message(message_text)
print(resp)

try:
intent = resp['entities']['intent'][0]['value']
except:
intent = None
try:
location = resp['entities']['location'][0]['value']
except:
location = None
try:
datetimefrom = resp['entities']['datetime'][0]['values'][0]['from']['value']
except:
datetimefrom = None
try:
datetimeto = resp['entities']['datetime'][0]['values'][0]['to']['value']
except:
datetimeto = None

resp 的示例。

{u'entities': {u'intent': [{u'confidence': 0.99699357488585, u'value': u'weather'}], u'location': [{u'suggested': True, u'confidence': 0.87101, u'type': u'value', u'value': u'like'}]}, u'msg_id': u'0jkzwqMkSkpZsKJYx', u'_text': u'What is the weather like?'}

最佳答案

如果不使用某种辅助函数或新容器,您将无法变得更短。一种方法是编写一个函数:

def try_get(obj, key):
if not key:
return obj

key, _, rest = key.partition('.')

try:
key = int(key)
except ValueError:
pass

try:
return try_get(obj[key], rest)
except (KeyError, IndexError):
return None

像这样使用它:

intent = try_get(resp, 'entities.intent.0.value')
location = try_get(resp, 'entities.location.0.value')
datetimefrom = try_get(resp, 'entities.datetime.0.values.0.from.value')
datetimeto = try_get(resp, 'entities.datetime.0.values.0.to.value')

JSON 不允许整数字典键,因此这应该明确允许您遍历从 JSON 解析的任何对象。

关于python - Python 中的尝试/异常(exception) : appropriate for parsing dictionaries?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46270763/

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