You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何基于部分IP字符串匹配提取路由器输出对应整行内容

错误原因分析
  • 第一个TypeError报错:re.finditer()要求第二个参数必须是字符串/字节类型,你用splitlines()把文件内容拆成了行列表,直接传入列表就触发类型错误。
  • 第二个IndexError报错:一方面是逻辑写反了,应该先存储test2的IP段集合,再逐行匹配test1的内容;另一方面split(None,1)[0]会在遇到空行、格式异常行时,拆分后列表长度不足1,触发索引越界。
实现方案

核心逻辑:先读取test2所有待匹配IP段存入集合,遍历test1的每一行,只要行中包含集合内的任意IP段,就直接输出整行即可,不需要额外拆分行格式。

# 读取test2的所有待匹配IP段,存入集合
with open('test2.txt', 'r', encoding='utf-8') as f:
    target_ips = {line.strip() for line in f if line.strip()}

# 遍历test1的每一行,匹配到IP就输出
with open('test1.txt', 'r', encoding='utf-8') as f:
    for line in f:
        line = line.rstrip('\n')
        for ip in target_ips:
            if ip in line:
                print(line)
                break

如果test1文件行数较多,可使用正则预编译提升匹配效率:

import re

with open('test2.txt', 'r', encoding='utf-8') as f:
    # re.escape处理IP中可能存在的特殊字符,避免正则匹配异常
    target_ips = [re.escape(line.strip()) for line in f if line.strip()]

# 编译正则,匹配任意一个目标IP段
pattern = re.compile('|'.join(target_ips))

with open('test1.txt', 'r', encoding='utf-8') as f:
    for line in f:
        if pattern.search(line):
            print(line.rstrip('\n'))

如果打开文件时报编码错误,可将encoding参数替换为gbk尝试适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:24:03