这段代码常因result结果出不来而无法继续运行,帮我加个条件判断,如果result没有结果的话重新运行这个filename,直到有结果为止。import csv import os import json from IPython import display pic_folder_path = "./期末作业-面部数据/face_images/a1" output_list = [] for filename in os.listdir(pic_folder_path): if filename.endswith(".jpg"): pic_path = os.path.join(pic_folder_path, filename) result = main(pic_path) # 调用主函数获取结果 if "result" not in result or "face_list" not in json.loads(result)["result"]: continue result_dict = json.loads(result)["result"]["face_list"] for item in result_dict: output_list.append({ "filename": filename, "type": item["emotion"]["type"] }) # 将结果保存为csv文件 with open("output.csv", "a", newline="") as f: writer = csv.DictWriter(f, fieldnames=["filename", "type"]) #writer.writeheader() writer.writerows(output_list)
时间: 2024-03-11 15:43:42 浏览: 88
CSharp操作Bios
可以在获取结果前加一个while循环,判断result是否有结果,如果没有结果则重新调用main函数,直到有结果为止。修改后的代码如下:
```python
import csv
import os
import json
from IPython import display
pic_folder_path = "./期末作业-面部数据/face_images/a1"
output_list = []
for filename in os.listdir(pic_folder_path):
if filename.endswith(".jpg"):
pic_path = os.path.join(pic_folder_path, filename)
result = None
while not result or "result" not in result or "face_list" not in json.loads(result)["result"]:
result = main(pic_path) # 调用主函数获取结果
result_dict = json.loads(result)["result"]["face_list"]
for item in result_dict:
output_list.append({
"filename": filename,
"type": item["emotion"]["type"]
})
# 将结果保存为csv文件
with open("output.csv", "a", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["filename", "type"])
# writer.writeheader()
writer.writerows(output_list)
```
这样修改后,如果result没有结果,就会重新调用main函数,直到有结果为止。
阅读全文