我正在使用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']

推荐答案

您可以try 使用re模块来完成任务:

import re

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},
}

pat = re.compile(r"^(?:\d+\.)?\s*(.+?)\s*$", flags=re.M)

for ch in response["choices"]:
    ch["text"] = pat.findall(ch["text"].strip())

print(response)

打印:

{
    "id": "xyz",
    "object": "text_completion",
    "created": 1673323957,
    "model": "text-davinci-003",
    "choices": [
        {
            "text": [
                "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",
            ],
            "index": 0,
            "logprobs": None,
            "finish_reason": "length",
        }
    ],
    "usage": {"prompt_tokens": 16, "completion_tokens": 100, "total_tokens": 116},
}

Json相关问答推荐

Jolt转换问题—使用键查找匹配对象

震击:三针并用震击

Python将Pandas转换为嵌套的JSON

如何在改装Android中将ResponseBody转换为JSONObject

(Kotlin)com.google.gson.internal.LinkedTreeMap无法转换为com.example.phonetest2.model.HallData

如何将属性拆分为嵌套的JSON内容?

使用 Groovy 将 XML 转换为 JSON

无法在Kotlin 中解析JSONObject

使用 KQL 和外部 data() 运算符从 json 文件中提取信息

使用 jq 获取特定键的所有父键

流编写器未写入 webapi 中的 JSON 文件

流导入错误:重新上传时不存在布局释放 UUID

在 postgresql 中将行转换为 json 对象

如何在 onClick 事件处理程序中识别在同一 map 上绘制的多个多边形中的哪个(使用 react-leaflet)被单击?

JSON.NET JsonConvert 与 .NET JavaScriptSerializer

将 PHP 结果数组转换为 JSON

使用 API 搜索维基百科

TypeError: b'1' 不是 JSON 可序列化的

MVC JsonResult camelCase 序列化

XML vs YAML vs JSON