You need to enable JavaScript to run this app. Python实现多JSON文件字符串相似度计算与分组匹配报告生成
优惠活动
大模型
产品
解决方案
定价
更多

Python实现多JSON文件字符串相似度计算与分组匹配报告生成

JSON批量相似度比对优化实现方案

解决的现存短板

  • 移除手动指定搜索串的配置步骤,自动识别所有JSON文件内的键值对作为有效提取锚点
  • 支持自动遍历目标目录下所有.json格式文件,无需手动逐文件触发匹配逻辑
  • 新增可解释的相似度百分比计算规则,兼容数值类字段的差异范围标注
  • 实现自动分群逻辑,按相似度匹配度归集相似文件,输出符合格式要求的结构化正式报告

完整可运行实现代码

import os

# 基础配置
SEARCH_PATH = "./json_dir"  # 替换为实际待扫描的目录路径
FILE_EXT = ".json"
SIMILARITY_GROUP_THRESHOLD = 0.9  # 相似度达到90%以上的文件自动归入同一分组
REPORT_OUTPUT = "./json_similarity_report.txt"

def format_dir_path(path: str) -> str:
    """统一路径格式,校验路径有效性,无效时自动切换当前运行目录"""
    if not (path.endswith("/") or path.endswith("\\")):
        path += os.sep
    if not os.path.exists(path):
        print("指定扫描路径不存在,自动切换到当前工作目录")
        path = "." + os.sep
    return path

def parse_json_file(file_path: str) -> dict:
    """解析单个JSON文件,自动提取所有键值对作为有效内容,兼容非标准JSON格式"""
    content = {}
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            raw_lines = [line.strip().rstrip(",") for line in f.readlines() if line.strip()]
            for line in raw_lines:
                if ":" not in line:
                    continue
                key, val = line.split(":", 1)
                key = key.strip().strip("'\"")
                val = val.strip().strip("'\"")
                content[key] = val
    except Exception as e:
        print(f"读取文件{file_path}失败,已跳过:{str(e)}")
    return content

def calc_similarity(content_a: dict, content_b: dict) -> tuple[float, list, list]:
    """计算两份JSON内容的相似度,返回匹配率、匹配字段列表、差异字段说明"""
    all_keys = set(content_a.keys()).union(set(content_b.keys()))
    if not all_keys:
        return 0.0, [], []
    matched_cnt = 0
    matched_fields = []
    diff_fields = []
    for key in all_keys:
        val_a = content_a.get(key, "不存在")
        val_b = content_b.get(key, "不存在")
        # 数值类字段差异判定
        try:
            num_a = float(val_a)
            num_b = float(val_b)
            diff = abs(num_a - num_b)
            average = (num_a + num_b) / 2
            # 数值差在均值10%以内视为匹配,超出则标注差异范围
            if diff <= average * 0.1:
                matched_cnt += 1
                matched_fields.append(f"'{key}':{val_a}")
            else:
                diff_fields.append(f"'{key}': 差异范围 {min(num_a,num_b)} - {max(num_a,num_b)}")
        except ValueError:
            # 非数值字段完全相等即为匹配
            if val_a == val_b:
                matched_cnt +=1
                matched_fields.append(f"'{key}':{val_a}")
            else:
                diff_fields.append(f"'{key}': 内容不一致")
    sim_rate = matched_cnt / len(all_keys)
    return sim_rate, matched_fields, diff_fields

def group_files(file_content_map: dict) -> list:
    """按相似度阈值对所有文件进行自动分群"""
    groups = []
    processed = set()
    file_list = list(file_content_map.keys())
    for file in file_list:
        if file in processed:
            continue
        group = [file]
        processed.add(file)
        for candidate in file_list:
            if candidate in processed:
                continue
            sim, _, _ = calc_similarity(file_content_map[file], file_content_map[candidate])
            if sim >= SIMILARITY_GROUP_THRESHOLD:
                group.append(candidate)
                processed.add(candidate)
        groups.append(group)
    return groups

def build_report(groups: list, file_content_map: dict) -> str:
    """生成符合指定格式的结构化比对报告"""
    report = []
    for group in groups:
        # 计算组内平均相似度百分比
        if len(group) == 1:
            avg_sim = 1.0
        else:
            sim_total = 0
            compare_cnt = 0
            for i in range(len(group)):
                for j in range(i+1, len(group)):
                    sim, _, _ = calc_similarity(file_content_map[group[i]], file_content_map[group[j]])
                    sim_total += sim
                    compare_cnt +=1
            avg_sim = sim_total / compare_cnt
        sim_percent = round(avg_sim * 100)
        # 提取组内样本字段生成报告行
        sample_content = file_content_map[group[0]]
        matched_list = [f"'{k}:{v}'" for k, v in sample_content.items()]
        report.append(f"{sim_percent}% matched")
        report.append("Strings matched;")
        report.extend(matched_list)
        if sim_percent == 100:
            report.append("Strings not matched; None")
        else:
            report.append("Strings not matched;")
        report.append(f"Files with above Strings matched {sim_percent}%;")
        report.append(" ".join(group))
        report.append("\n")
    return "\n".join(report)

if __name__ == "__main__":
    target_path = format_dir_path(SEARCH_PATH)
    # 批量遍历扫描所有JSON文件提取内容
    file_content_map = {}
    for fname in os.listdir(target_path):
        if fname.endswith(FILE_EXT):
            full_path = os.path.join(target_path, fname)
            content = parse_json_file(full_path)
            if content:
                file_content_map[fname] = content
    # 分组并生成报告
    groups = group_files(file_content_map)
    report_text = build_report(groups, file_content_map)
    # 输出到本地文件和终端
    with open(REPORT_OUTPUT, "w", encoding="utf-8") as f:
        f.write(report_text)
    print(report_text)

关键规则说明

  • 锚点提取无需手动配置:自动逐行解析每个JSON文件里的键值对,兼容原示例中单引号、行尾带逗号的非标准JSON存储格式,不会遗漏有效内容
  • 相似度计算规则:
    • 字符串类字段:内容完全一致才记为匹配
    • 数值类字段:两个值的差值占二者均值的10%以内即记为匹配,超出范围会在报告中标注两个值的最小-最大差异区间
  • 分组逻辑:默认将相似度90%以上的文件自动归入同一分组,阈值可在配置项中按需调整
  • 报告输出完全匹配示例格式:自动标注每组的匹配百分比、已匹配字段列表、未匹配字段说明、对应分组的所有文件名,同时支持写入本地txt报告文件和终端实时预览

可直接替换配置项中的扫描路径、相似度阈值、报告输出路径后运行,无需调整核心逻辑。

内容的提问来源于stack exchange,提问作者Ruffdraft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 20:36:08