使用正则表达式使用Python从日志文件中提取文件名

问题描述 投票:0回答:1

希望创建从日志文件访问的文件列表。下面显示了文件中字符串的两个示例。

.... [08 / Mar / 2020:19:11:15 -0700]“ GET / socview / 15Ragged.htm HTTP / 1.1” 200 6564 .........

.... [08 / Mar / 2020:19:11:31 -0700]“ GET / socview /?C = D; O = A HTTP / 1.1” 200 13443 ...... ........

/ socview / 15Ragged.htm是我要提取的内容。以.htm .log .txt等结尾]

/ socview /?C = D; O = A是我要避免提取的内容。

似乎是“。”是什么引起了问题,例如当我在不搜索代码的情况下运行代码时。下面的RE可以完美运行,作为本文底部所示循环的一部分。

unique = re.search(r'GET (\S+)', x)

但是它正在提取我不想要的字符串。以下是我要使用的循环和RE,对我来说很有意义,当运行以下消息时,我无法弄清楚出了什么问题。任何帮助将不胜感激

“如果unique.group(1)不在unilist中:

[AttributeError:'NoneType'对象没有属性'group'“]

for x in input:
     unique = re.search(r'GET (\S+\.\S+)', x)

     if unique.group(1) not in unilist:
           unilist.append(unique.group(1))
python regex logfile
1个回答
0
投票

GET (\S+\.\S+)很好。问题是如果匹配失败,re.search()返回None,那么对于您提供的第二个字符串,unique是不具有None属性的group

尝试以下操作:

for x in input:
    unique = re.search(r'GET (\S+\.\S+)', x)

    if unique is None:
        continue

    if unique.group(1) not in unilist:
           unilist.append(unique.group(1))

我建议您使用更好的变量名。例如,input是Python的内置程序,请避免对其进行阴影处理。如果循环体增大,将很难遵循x之类的名称。

此外,我建议像这样预编译正则表达式,否则它将在每个周期中进行编译,这非常耗时:

matcher = re.compile("GET (\S+\.\S+)")

for line in lines:
    # your loop body here
© www.soinside.com 2019 - 2024. All rights reserved.