1. 首页 > SEO工具 > 搜索引擎SEO工具

python代码:提取日志文件中的ip,并统计抓取次数,按降序排列,保存为txt文件

# -*- coding: utf-8 -*-
# 网站日志IP统计,输出txt,格式:IP:访问次数(一行一个)
def count_ip_from_log():
    # ====================== 需修改的配置 开始 ======================
    log_file_path = r"C:\Users\EDY\Desktop\工作\sitemap\日志查询\www.lubanseo.com.log"  # 你的本地日志文件路径
    save_txt_path = r"C:\Users\EDY\Desktop\工作\sitemap\日志查询\ip统计结果.txt"  # 统计结果保存的txt路径+文件名
    # ====================== 需修改的配置 结束 ======================
    ip_count = {}  # 字典存储:key=ip地址,value=访问次数
    # 读取日志文件,逐行处理,不占内存,支持大文件
    with open(log_file_path, 'r', encoding='utf-8', errors='ignore') as f:
        for line in f:
            line = line.strip()
            if not line:  # 跳过空行
                continue
            # 提取每行的第一个字段【就是日志的IP】,网站日志通用格式都是开头为IP
            ip = line.split()[0]
            # 统计次数:存在则+1,不存在则初始化为1
            ip_count[ip] = ip_count.get(ip, 0) + 1
    # ========== 新增核心排序:按访问次数 从多到少 降序排列 ==========
    # reverse=True 降序 | reverse=False 升序
    sorted_ip_count = sorted(ip_count.items(), key=lambda x: x[1], reverse=True)
    # 将排序后的统计结果写入txt文件,严格按【ip:次数】一行一个的格式
    with open(save_txt_path, 'w', encoding='utf-8') as txt_f:
        for ip, num in sorted_ip_count:
            txt_f.write(f"{ip}:{num}\n")
    print(f"✅ 统计完成!结果已保存至:{save_txt_path}")
    print(f"✅ 共统计到【{len(ip_count)}】个独立IP")
# 执行程序
if __name__ == '__main__':
    count_ip_from_log()

声明:本文网友投稿,观点仅代表作者本人,不代表鲁班SEO赞同其观点或证实其描述。

联系我们

在线咨询:点击这里给我发消息

微信号:

工作日:9:30-18:30,节假日休息