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

Python搜索log文件匹配指定字符串提取检测器编号出现TypeError如何解决

错误原因

报错的核心原因是re.search()方法的返回值是正则匹配对象(Match对象),不是匹配到的原始字符串:
你代码中findLine = re.search(pattern, line)执行后,当匹配成功时findLine是Match对象,你直接把这个对象传给detectorPattern.search(findLine),而该方法要求传入的参数是字符串/字节类型,因此触发类型错误。

另外你的代码还存在三处隐藏问题:

  • 遍历文件打印文件名时错误写为directory[1],会始终打印目录下第二个文件的名称
  • 检测器编号的正则\d\d.\d\d\d中.没有转义,正则里的.会匹配任意字符,无法严格匹配数字.数字的格式
  • 没有判断检测器编号是否匹配成功,直接调用.group()可能触发空指针报错
修复方案

将传入detectorPattern.search()的参数改为当前读取的行字符串line,同时修复其他隐藏问题,修改后代码如下:

import os
import re

pattern = input("What are you searching for? -->")
# 正则转义点号,严格匹配XX.XXX格式的检测器编号
detectorPattern = re.compile(r'\d\d\.\d\d\d')
directory = os.listdir()
for x in range(len(directory)):
    current_file = directory[x]
    # 过滤只处理log文件,避免打开目录/其他格式文件报错
    if not current_file.endswith('.log'):
        continue
    with open(current_file, 'r', encoding='utf-8') as reader:
        print("Opening " + current_file)
        for line in reader:
            # 纯字符串关键词判断用in比re.search效率更高
            if pattern in line:
                mo = detectorPattern.search(line)
                # 匹配到检测器编号再输出,避免空指针报错
                if mo:
                    print(mo.group())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:09:01