在日志文件中,我在每一行上都有以下格式:
[date] [thread] [loglevel] [class] some text describing the event that happened.
我想遍历日志并拆分字符串,以便获得以下内容:['date','thread','loglevel','class','描述所发生事件的一些文本。']
我很确定我需要使用 re.split 来执行此操作,但我的正则表达式很糟糕。
尝试这样的事情:
for line in open(sys.argv[1]).xreadlines():
parts = re.split(r'[[]]',line)
感谢任何帮助!
试试这个:
>>> log = '[date] [thread] [loglevel] [class] some text describing the event that happened.'
>>> [part.strip() for part in re.split('[\[\]]', log) if part.strip()]
['date', 'thread', 'loglevel', 'class', 'some text describing the event that happened.']
字符串在遇到 [ 或 ] 时被拆分。在 re.split 的模式中,您需要转义这些字符。我添加了 part.strip() 和 if part.strip() 以删除不需要的空格和空字符串
我是一名优秀的程序员,十分优秀!