Python处理日志文件并去除字符

2 投票
2 回答
1200 浏览
提问于 2025-04-16 11:00

我正在制作一个快速的日志解析工具:

findme = 'important '
logf = file('new.txt')
newlines = []

    for line in logf:
        if findme in line:
            line.partition("as follows: ")[2]
            newlines.append(line) 


outfile = file('out.txt', 'w')
outfile.writelines(newlines)

我不太确定该怎么用像 partition 这样的东西来逐行去掉 "as follows: " 以及它前面的所有文字。我没有遇到错误,但我想去掉的文字还是出现在输出结果里。

2 个回答

1

这里是关于正则表达式的内容

import re

findme = 'important ' 
pat = re.compile('.*(%s)?.*as follows: ((?(1).*\n|.*%s.*\n))' % (findme,findme))

with open('new.txt','r') as logf, open('out.txt','w') as outfile:
    for line in logf:
        m = pat.match(line)
        if m: outfile.write( m.group(2) )

使用正则表达式的好处是,它可以让你搜索到比单纯用'if findme in line'指令更具体的内容。比如,使用findme = '(?<!A)AAA(?!A)',它会严格按照'AAA'来搜索,而不是像'AAAA'这样的内容。

3

另外,我对这一行有点困惑

line.partition("as follows: ")[2]

。它实际上没有任何作用。也许你想要的是

line = line.partition("as follows")[2]

?顺便说一下,最好在for循环中逐行写,而不是最后用一个巨大的 writelines。你现在的做法在处理大文件时会占用很多内存,对于无限大的文件根本无法使用。

最终版本应该是这样的:

findme = 'important '
outfile = open('out.txt', 'w')
for line in open('new.txt'):
    if findme in line:
        outfile.write(line.partition('as follows: ')[2])

撰写回答