我正在使用OpenAI API,并按如下方式返回JSON对象:
response = {'id': 'xyz',
'object': 'text_completion',
'created': 1673323957,
'model': 'text-davinci-003',
'choices': [{'text': '\n\n1. Dog Diet and Nutrition \n2. Dog Vaccination and Immunization \n3. Dog Parasites and Parasite Control \n4. Dog Dental Care and Hygiene \n5. Dog Grooming and Skin Care \n6. Dog Exercise and Training \n7. Dog First-Aid and Emergency Care \n8. Dog Joint Care and Arthritis \n9. Dog Allergies and Allergy Prevention \n10. Dog Senior Care and Health',
'index': 0,
'logprobs': None,
'finish_reason': 'length'}],
'usage': {'prompt_tokens': 16, 'completion_tokens': 100, 'total_tokens': 116}}
对于字典中的choices
,更具体地说,对于字典中只有text
的键,我如何在键text
的字符串中用逗号分隔的列表为我们看到\n2.
的每个枚举替换键text
的值,并用空替换每个\n\n1.
的值?此外,API有点挑剔,有时响应不会返回数字,只返回\n\n
或\n
.理想情况下,解决方案可以灵活地处理这一点,但如果不是这样,也没问题.
我想把choices
取到一个新的变量中.
新的choices
强榜单应该是这样的:
new_choices = ['Dog Diet and Nutrition', 'Dog Vaccination and Immunization', 'Dog Parasites and Parasite Control', 'Dog Dental Care and Hygiene', 'Dog Grooming and Skin Care', 'Dog Exercise and Training', 'Dog First-Aid and Emergency Care', 'Dog Joint Care and Arthritis', 'Dog Allergies and Allergy Prevention', 'Dog Senior Care and Health']
我试过这个代码,得到了列表中的一半,但在一些地方留下了数字,并添加了多个逗号,我不知道从哪里开始,特别是go 掉数字并用逗号取代它们:
new_choices = [response.json()['choices'][0]['text'].replace('\n',',')]
结果:
[',,1. Dog Diet and Nutrition ,2. Dog Vaccination and Immunization ,3. Dog Parasites and Parasite Control ,4. Dog Dental Care and Hygiene ,5. Dog Grooming and Skin Care ,6. Dog Exercise and Training ,7. Dog First-Aid and Emergency Care ,8. Dog Joint Care and Arthritis ,9. Dog Allergies and Allergy Prevention ,10. Dog Senior Care and Health']