如何将OpenAI调用的结果转换为JSON并写入.txt文件?

我对Python非常陌生,只知道一些基础知识。我正在调用OpenAI并获取响应,现在我想将这个响应写入一个.txt文件中。

我想在写入文件之前将响应转换为JSON格式。我的响应已经是JSON格式,但当我打印时,它显示为带有json {} 的JSON格式。这是我的脚本

def get_json(image_file, category):    with open(image_file, "rb") as image:        response = openai_client.chat.completions.create(            model="gpt-4-vision-preview",            messages=[                {                    "role": "user",                    "content": [                        {"type": "text", "text": f"Analyze this image and provide the following attributes: color theme, font style, and a short description of about 4-7 words. Categorize it as {category}. Return the result as a JSON object."},                        {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64.b64encode(image.read()).decode()}"}},                    ],                }            ],            temperature=1,            max_tokens=4095,            top_p=1,            frequency_penalty=0,            presence_penalty=0,        )         return response.choices[0].message.content     with open(file, 'a') as file:    for filename in os.listdir(images_folder):        filepath = os.path.join(images_folder, filename)        result =get_json(filepath, 'hero')        file.write(result + '\n')        json_result = json.loads(result)        print(json_result)

这是我得到的结果enter image description here

我想去掉文本”’json”’

尝试通过json.loads(result)将其转换为JSON,但得到以下错误:-raise JSONDecodeError(“Expecting value”, s, err.value) from Nonejson.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)


回答:

你在提示中要求它返回一个JSON对象,“Return the result as a JSON object.” 这就是原因!如果你在网站上使用相同的提示,你会注意到响应格式很好,这是因为那些““`json …content “`”的markdown格式化。

你可以使用两种方法来解决这个问题:

  1. 明确地用空字符串替换““`json”和““`”:
import json# 例如,这是响应中的内容:response = '```json{"color_theme": "Mint Green and Black","font_style": "Sans-serif","short_description": "Web Publishing Platform","category": "hero"}```'# 替换并重新赋值给原始内容response = response.replace("```json", "")response = response.replace("```", "")# 别忘了转换为JSON,因为它现在是一个字符串:json_result = json.loads(response)
  1. 使用切片:
import json# 例如,这是响应中的内容:response = '```json{"color_theme": "Mint Green and Black","font_style": "Sans-serif","short_description": "Web Publishing Platform","category": "hero"}```'# “```json”长度为7个字符,但切片计数从0开始。“{”位于第7个字符。# “```”长度为3个字符(在末尾)。response = response[7:-3]# 别忘了转换为JSON,因为它现在是一个字符串:json_result = json.loads(response)

至于写入.txt文件,你可以使用json.dump()如下所示:

import jsonresponse = '```json{"color_theme": "Mint Green and Black","font_style": "Sans-serif","short_description": "Web Publishing Platform","category": "hero"}```'response = response[7:-3]response = json.loads(response)# 写入response.txt文件(覆盖它)。with open("response.txt", "w") as file:    json.dump(response, file)

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注