You need to enable JavaScript to run this app. 使用Python解析大型CSV IRC日志,统计互相提及次数最多的用户名配对
优惠活动
大模型
产品
解决方案
定价
更多

使用Python解析大型CSV IRC日志,统计互相提及次数最多的用户名配对

IRC日志用户名提及配对统计实现方案

前置说明

5万行的CSV文件属于极小数据规模,不需要任何特殊的大数据处理方案,直接用Python标准库逐行读取即可,全程内存占用不会超过100MB,完全可以在普通消费级设备上流畅运行。

核心实现逻辑

  • 首次遍历日志文件,收集所有消息类型为1的用户名,存入集合用于后续匹配提及
  • 二次遍历日志文件,只处理消息类型为1的行:
    • 提取发送者用户名和消息内容
    • 在消息内容中匹配所有出现的其他用户名
    • 将发送者和被提及者按固定顺序(如字母序)拼接为配对键,避免(A,B)和(B,A)被识别为不同配对
    • 累加配对的提及次数
  • 遍历完成后输出计数最高的配对即可

完整实现代码

import csv
import re
from collections import defaultdict

# 配置项
CSV_PATH = "你的日志文件路径.csv"
# 用户名全词匹配正则,避免部分匹配误判
USER_PATTERN_TPL = r"\b{}\b"

# 第一步:收集所有有效用户名
usernames = set()
with open(CSV_PATH, 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        # 跳过格式错误行和非用户消息行
        if len(row) <4 or row[0].strip() != '1':
            continue
        username = row[2].strip('"')
        usernames.add(username)

# 编译正则匹配规则,提升匹配效率
username_re = re.compile(
    '|'.join(USER_PATTERN_TPL.format(re.escape(u)) for u in usernames),
    flags=re.IGNORECASE  # 如果提及用户名不区分大小写可以保留,不需要就删掉
)

# 第二步:统计提及配对次数
pair_count = defaultdict(int)
with open(CSV_PATH, 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        if len(row) <4 or row[0].strip() != '1':
            continue
        sender = row[2].strip('"')
        content = row[3].strip('"')
        # 匹配消息中所有提到的用户名
        mentioned_users = set(username_re.findall(content))
        # 排除自己提到自己的情况,不需要可以删掉下面两行
        if sender in mentioned_users:
            mentioned_users.remove(sender)
        # 计数
        for mention in mentioned_users:
            # 统一配对顺序,保证双向提及都计入同一个键
            pair = tuple(sorted((sender, mention)))
            pair_count[pair] += 1

# 输出提及次数最多的前10个配对
sorted_pairs = sorted(pair_count.items(), key=lambda x:x[1], reverse=True)
print("提及次数最多的用户名配对:")
for pair, cnt in sorted_pairs[:10]:
    print(f"{pair[0]} 和 {pair[1]}:{cnt} 次")

注意事项

  • 如果后续处理更大的日志文件,该逻辑依然适用,全程只有用户名集合和计数字典会存入内存,不需要加载全量日志
  • 如需调整输出的配对数量,修改sorted_pairs[:10]里的数字即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 01:54:06