SunSec's picture
Add files using upload-large-folder tool
4ac1fc5 verified
import json
from collections import defaultdict,OrderedDict, Counter
from tqdm import tqdm
import random
import matplotlib.pyplot as plt
def save_to_json(data, filename):
"""保存数据到 JSON 文件"""
with open(filename, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
print(f"Saved to {filename}, data length: {len(data)}")
def load_json(file_path):
"""从 JSON 文件加载数据"""
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
print(f"Loaded from {file_path}, data length: {len(data)}")
return data
def analyze_and_visualize_sources(final_dataset, output_image_path="source_distribution_selected_data.png", output_json_path="source_counts.json"):
"""
统计 final_dataset 中 source 的分布,并绘制饼图和保存为 JSON 文件。
:param final_dataset: 输入的数据列表,每个元素是一个字典
:param output_image_path: 饼图保存路径(默认为 "source_distribution.png")
:param output_json_path: JSON 文件保存路径(默认为 "source_counts.json")
"""
# 提取所有包含 source 的项
sources = [item["source"] for item in final_dataset if "source" in item]
# 统计 source 的分布
source_counts = Counter(sources)
# 将统计结果保存为 JSON 文件
with open(output_json_path, "w", encoding="utf-8") as f:
json.dump(source_counts, f, ensure_ascii=False, indent=4)
print(f"Source 分布已保存到 {output_json_path}")
# 绘制饼图
labels = list(source_counts.keys())
counts = list(source_counts.values())
plt.figure(figsize=(8, 8))
plt.pie(counts, labels=labels, autopct='%1.1f%%', startangle=140)
plt.title("Source Distribution")
plt.axis('equal') # 确保饼图为正圆
# 保存饼图为图片文件
plt.savefig(output_image_path)
plt.close()
print(f"Source 分布饼图已保存到 {output_image_path}")
input_file = "/share/project/sunshuang/deep_search/data_syn/data/mixed_data/mixed_data_all.json"
data = load_json(input_file)
analyze_and_visualize_sources(data)