惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
宝玉的分享
宝玉的分享
IT之家
IT之家
Recent Announcements
Recent Announcements
T
The Blog of Author Tim Ferriss
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
M
MIT News - Artificial intelligence
D
Docker
C
CERT Recently Published Vulnerability Notes
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Recorded Future
Recorded Future
博客园 - 司徒正美
D
DataBreaches.Net
Last Week in AI
Last Week in AI
U
Unit 42
人人都是产品经理
人人都是产品经理
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
量子位
大猫的无限游戏
大猫的无限游戏
博客园 - Franky
T
Tailwind CSS Blog
小众软件
小众软件
Y
Y Combinator Blog
WordPress大学
WordPress大学
B
Blog RSS Feed
C
Check Point Blog
H
Help Net Security
The Last Watchdog
The Last Watchdog
F
Full Disclosure
腾讯CDC
V
Visual Studio Blog
Google Online Security Blog
Google Online Security Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Troy Hunt's Blog
N
News and Events Feed by Topic
F
Fortinet All Blogs
B
Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
J
Java Code Geeks
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
有赞技术团队
有赞技术团队
博客园 - 三生石上(FineUI控件)
TaoSecurity Blog
TaoSecurity Blog
I
InfoQ
V
Vulnerabilities – Threatpost

博客园 - VipSoft

Python 项目简单部署(Linux) MinerU - 将非结构化文档(PDF、图片、Office 文件等)转换为机器可读的 Markdown 和 JSON LangChain 入门 服务端部署-FastAPI LangChain 入门 LangSmith LangChain 入门 实战 - 食谱推荐 LangChain 入门 Memory 会话记忆 LangChain 入门 Tools 工具 LangChain 入门 Tools 工具 LangChain 入门 Prompts 提示词 LangChain 入门 Message 消息 LangChain 入门 Model 的初始化和调用 LangChain 入门 Agent 的基本运行机制 AI 0基础学习,名词解析 LangChain 和 LangGraph AI大模型知识体系 Dify — Workflow - 数据可视化 Dify — 连接MySQL配置 Dify — Chatflow - 数据库智能查询 Dify — Chatflow - 文档知识库 Dify — Agent 智能体 高安全券码、注册码生成 Dify — 文本生成应用 Dify — 聊天助手 -- 知识库 Windows 下 Docker 安装 Dify Ollama — 命令 Ollama — 为什么能够运行不同的模型 Ollama — 接口 Qwen — 自定义模型文件 Ollama Qwen — 安装测试 Ollama Windows 安装 & 指定安装目录 跟着AI学AI - 诊断结论信息抽取 - 批量处理脚本 跟着AI学AI - 诊断结论信息抽取 - 模型压缩与部署 跟着AI学AI - 诊断结论信息抽取 - 模型评估与调试 跟着AI学AI - 诊断结论信息抽取 - 模型训练 轻型民用无人驾驶航空器安全操控理论考试培训材料 FreeRedis Helper Windbg w3wp.DMP 内存分析 跟着AI学AI - 诊断结论信息抽取 - 数据增强 QQ 录屏软件 Java - 加权随机算法 - 示例 Java - 加权随机算法--Demo Java LoadBalanceUtil 负载均衡、轮询加权 SpringBoot 集成 IP2Region 获取IP地域信息 Windows 服务器和虚拟主机,创建.开头的文件夹 .well-known 跟着AI学AI - 诊断结论信息抽取 - 数据格式转换BERT训练格式 跟着AI学AI - 诊断结论信息抽取 - LabelStudio 标注 -- 结论标注 跟着AI学AI - 诊断结论信息抽取 - 学习路径 跟着AI学AI - UV 安装 数据标注工具 Label-Studio `VIRTUAL_ENV=venv` does not match the project environment 跟着AI学AI - 学习路径 - 命名实体识别(NER)和信息抽取(IE) 跟着AI学AI - 需要购买显卡吗? C# 无BOM的UTF-8编码 Vue ref reactive Vue - el-table 嵌套表 Spring `@Scheduled` 中这些参数的区别、组合和应用场景 Python - UV PyCharm 不能识别 .venv 的环境
Python 找出同步日志中的重复数据
VipSoft · 2026-01-07 · via 博客园 - VipSoft

在做接口对接时,对方提交过来的数据存在重复数据,这时候可以通过 Python 轻松提取出来
syncDevice_2026-01-07.log

2026-01-07 11:41:33 | [{"deviceMac":"ED:0C:51:C2:B2:EA","deviceSn":"240103P50162"},{"deviceMac":"C0:7A:A1:6C:67:AA","deviceSn":"221130P50012"},{"deviceMac":"D0:D0:02:39:83:D4","deviceSn":"221130P50012"}]
2026-01-07 11:41:33 | [{"deviceMac":"D0:D0:02:39:83:D4","deviceSn":"221130P50012"},{"deviceMac":"DC:8E:33:BA:3D:6D","deviceSn":"221130P50013"}]

Python 代码如下:

import json
import re
from collections import defaultdict


def find_duplicate_devices_unique_mac(log_file_path):
    # 按 deviceSn 分组,每组内用集合去重 deviceMac
    devices_by_sn = defaultdict(list)
    mac_seen_by_sn = defaultdict(set)  # 用于跟踪每个 SN 下已见过的 deviceMac

    # 读取日志文件
    with open(log_file_path, 'r', encoding='utf-8') as file:
        for line_num, line in enumerate(file, 1):
            # 使用正则表达式提取 JSON 部分
            match = re.search(r'\[.*\]', line)
            if match:
                try:
                    # 解析 JSON 数组
                    devices = json.loads(match.group())

                    # 将每个设备添加到对应 deviceSn 的分组中,并去重 deviceMac
                    for device in devices:
                        device_sn = device.get('deviceSn')
                        device_mac = device.get('deviceMac')

                        if device_sn and device_mac:
                            # 如果这个 SN 下还没见过这个 MAC,则添加
                            if device_mac not in mac_seen_by_sn[device_sn]:
                                devices_by_sn[device_sn].append(device)
                                mac_seen_by_sn[device_sn].add(device_mac)
                except json.JSONDecodeError as e:
                    print(f"第 {line_num} 行解析 JSON 时出错: {e}")
                    continue

    # 找出重复的 deviceSn(去重 MAC 后仍然有多个记录的)
    duplicate_devices = {}
    for device_sn, devices in devices_by_sn.items():
        if len(devices) > 1:
            duplicate_devices[device_sn] = devices

    return duplicate_devices


def print_duplicate_devices(duplicate_devices):
    if not duplicate_devices:
        print("没有找到重复的 deviceSn")
        return

    print("找到以下重复的 deviceSn (已对 deviceMac 去重):\n")
    for device_sn, devices in duplicate_devices.items():
        print(f"deviceSn: {device_sn} (去重后出现 {len(devices)} 次)")
        print("-" * 50)

        for i, device in enumerate(devices, 1):
            print(f"第 {i} 条记录:")
            # 美化输出 JSON
            print(json.dumps(device, indent=2, ensure_ascii=False))
            print()

        print("=" * 80)


# 版本2:更简洁的实现,直接输出去重结果
def find_and_print_duplicates_unique(log_file):
    # 存储去重后的设备
    unique_devices_by_sn = defaultdict(list)
    seen_mac_by_sn = defaultdict(set)

    with open(log_file, 'r') as f:
        for line in f:
            # 提取 JSON 数组部分
            json_match = re.search(r'\[.*\]', line)
            if json_match:
                try:
                    devices = json.loads(json_match.group())
                    for device in devices:
                        sn = device.get('deviceSn')
                        mac = device.get('deviceMac')

                        if sn and mac:
                            # 如果这个 MAC 还没在这个 SN 组中出现过
                            if mac not in seen_mac_by_sn[sn]:
                                unique_devices_by_sn[sn].append(device)
                                seen_mac_by_sn[sn].add(mac)
                except:
                    continue

    # 找出并打印重复项
    print("重复的设备SN及其数据 (已对deviceMac去重):")
    print("=" * 80)

    found_duplicates = False
    for sn, devices in unique_devices_by_sn.items():
        if len(devices) > 1:
            found_duplicates = True
            print(f"\n设备SN: {sn} (去重后出现 {len(devices)} 次)")
            print("-" * 50)

            for i, device in enumerate(devices, 1):
                print(f"记录 {i}:")
                # 格式化时间戳
                if 'productionDate' in device:
                    import datetime
                    timestamp = device['productionDate'] / 1000
                    dt = datetime.datetime.fromtimestamp(timestamp)
                    device['productionDate_formatted'] = dt.strftime('%Y-%m-%d %H:%M:%S')

                print(json.dumps(device, indent=2, ensure_ascii=False))
                print()

    if not found_duplicates:
        print("没有找到重复的 deviceSn (或所有重复都是相同的 deviceMac)")


# 主程序
if __name__ == "__main__":
    log_file_path = "syncDevice_2026-01-07.log"

    try:
        print("=" * 80)
        print("方法1:详细版")
        print("=" * 80)
        # 查找重复设备(去重 MAC)
        duplicate_devices = find_duplicate_devices_unique_mac(log_file_path)

        # 打印结果
        print_duplicate_devices(duplicate_devices)

        # 统计信息
        print("\n统计信息:")
        print(f"总共有 {len(duplicate_devices)} 个重复的 deviceSn")
        for device_sn, devices in duplicate_devices.items():
            print(f"  - {device_sn}: {len(devices)} 条不重复的记录")

        print("\n" + "=" * 80)
        print("方法2:简洁版")
        print("=" * 80)
        find_and_print_duplicates_unique(log_file_path)

    except FileNotFoundError:
        print(f"错误: 找不到文件 {log_file_path}")
    except Exception as e:
        print(f"处理文件时出错: {e}")

输入结果:

================================================================================
方法1:详细版
================================================================================
找到以下重复的 deviceSn (已对 deviceMac 去重):

deviceSn: 221130P50012 (去重后出现 2 次)
--------------------------------------------------
第 1 条记录:
{
  "deviceMac": "C0:7A:A1:6C:67:AA",
  "deviceSn": "221130P50012"
}

第 2 条记录:
{
  "deviceMac": "D0:D0:02:39:83:D4",
  "deviceSn": "221130P50012"
}

================================================================================

统计信息:
总共有 1 个重复的 deviceSn
  - 221130P50012: 2 条不重复的记录

================================================================================
方法2:简洁版
================================================================================
重复的设备SN及其数据 (已对deviceMac去重):
================================================================================

设备SN: 221130P50012 (去重后出现 2 次)
--------------------------------------------------
记录 1:
{
  "deviceMac": "C0:7A:A1:6C:67:AA",
  "deviceSn": "221130P50012"
}

记录 2:
{
  "deviceMac": "D0:D0:02:39:83:D4",
  "deviceSn": "221130P50012"
}


Process finished with exit code 0