import json | |
# 定义文件路径 | |
json_path = '/home/yiyangai/stephenqs/datasets/wikihow/health-filtered-updated.json' | |
output_json_path = '/home/yiyangai/stephenqs/datasets/wikihow/health-filtered-relative.json' | |
# 定义需要替换的路径 | |
old_path = '/home/yiyangai/stephenqs/datasets/wikihow/' | |
new_path = './' | |
# 读取JSON文件 | |
with open(json_path, 'r', encoding='utf-8') as file: | |
data = json.load(file) | |
# 遍历所有方法和步骤以替换路径 | |
for example in data: | |
for method in example.get("methods", []): | |
for step in method.get("steps", []): | |
img_path = step.get("img") | |
if img_path and img_path.startswith(old_path): | |
# 替换路径前缀为 './' | |
step["img"] = img_path.replace(old_path, new_path, 1) | |
# 将更新后的数据保存到一个新的JSON文件 | |
with open(output_json_path, 'w', encoding='utf-8') as outfile: | |
json.dump(data, outfile, ensure_ascii=False, indent=4) | |
print("路径替换完成,JSON文件已更新并保存。") | |