我对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格式化。
你可以使用两种方法来解决这个问题:
- 明确地用空字符串替换““`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)
- 使用切片:
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)