【问题标题】:filter a Linux log file using Python使用 Python 过滤 Linux 日志文件
【发布时间】:2014-02-06 04:00:39
【问题描述】:

我想过滤一个日志文件以保持所有行匹配特定模式。我想用 Python 做到这一点。

这是我的第一次尝试:

#!/usr/bin/env python

from sys import argv 

script, filename = argv
with open(filename) as f:
    for line in f:
        try:
            e = line.index("some_term_I_want_to_match")
        except: 
            pass
        else:
            print(line)

我该如何改进:

  • 将结果保存到名称相似的新文件中(即不同的扩展名)
  • 使用正则表达式使其更加灵活/强大。

(我只是在学习 Python。这个问题既是关于学习 Python,也是关于完成这个特定的结果。)

好的,这就是我到目前为止的想法......但是你如何做相当于在下面的行中添加r

re.compile(r"\s*")

其中的字符串不是字符串文字,如下一行所示?

re.compile(a_string_variable)

除此之外,我认为这个更新版本可以完成这项工作:

#!/usr/bin/env python

from sys import argv 
import re
import os
import argparse #requires Python 2.7 or above

parser = argparse.ArgumentParser(description='filters a text file on the search phrase')
parser.add_argument('-s','--search', help='search phrase or keyword to match',required=True)
parser.add_argument('-f','--filename', help='input file name',required=True)
parser.add_argument('-v','--verbose', help='display output to the screen too', required=False, action="store_true")
args = parser.parse_args()

keyword = args.search
original_file = args.filename
verbose = args.verbose

base_file, ext = os.path.splitext(original_file)
new_file = base_file + ".filtered" + ext

regex_c = re.compile(keyword)

with open(original_file) as fi:
    with open(new_file, 'w') as fo:
        for line in fi:
            result = regex_c.search(line)
            if(result):
                fo.write(line)
                if(verbose):
                    print(line)

这可以轻松改进吗?

【问题讨论】:

  • 为什么不使用grep?如果您想使用正则表达式并坚持用 Python 编写,请查看 re 模块。
  • 我认为这里不需要try...except
  • 我更新了我的问题。我想用 Python 来做这件事,因为我正在学习 Python。

标签: python regex linux filter


【解决方案1】:

嗯,你知道,你自己已经回答了大部分问题:)

对于正则表达式匹配,请使用re module(文档中有很好的解释性示例)。

您已经使用open() 函数打开文件。对打开的文件使用相同的函数进行写入,只需提供相应的mode 参数(如果需要,“w”或“a”与“+”组合,请参阅 Python 交互式 shell 中的help(open))。就是这样。

【讨论】:

  • ... 并使用os.path 模块更改文件扩展名。
  • 嗯,“改进”不是描述您的需求的正确词。如果它做你想要的,它不应该被改进。如果你还需要其他东西,你应该明确地制定它。我会通过在一个语句中合并两个文件打开来降低嵌套级别,但这需要一个实现Context Manager protocol 的对象。或者干脆使用try: f = open("original")... finally: f.close()...,意思和with声明几乎一样
猜你喜欢
  • 2015-10-20
  • 2014-07-22
  • 1970-01-01
  • 2018-07-26
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 2011-10-29
相关资源
最近更新 更多