使用python正则表达式解析具有不同块的值的特定单词

2024-03-28 15:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Python正则表达式从3GB日志文件中提取元组形式的数据。你知道吗

日志格式如下。你知道吗

2012-11-22 08:57:25,232 [P:DEBUG] moteId=245 statusElem=1
2012-11-22 08:57:25,042 [P:DEBUG] parsed into Tuple_IsSync(isSync=1)
2012-11-22 08:57:26,128 [P:DEBUG] parsed into Tuple_ScheduleRow(row=9, slotOffset=9, type=6, shared=0, channelOffset=0, neighbor_type=0, neighbor_bodyH=0, neighbor_bodyL=0, backoffExponent=1, backoff=0, numRx=0, numTx=0, numTxACK=0, lastUsedAsn_4=0, lastUsedAsn_2_3=0, lastUsedAsn_0_1=0, next=7638)

我想要元组:

(2012-11-22, 08:57:25,042, moteId=245, statusElem=1, isSync=1, numRx=0, numTx=0, numTxACK=0,)

在一条线上。你知道吗

import re
import sys

files=open('/Users/s/Desktop/p.log','r')

match=re.findall(r'\w[\s*moteId\s(statusElem)(isSync)(numTxAck).*]+.\d+',files.read())
f=open('/Users/s/Desktop/w.txt','w')
f.writelines(match)
f.close()

我的代码没有完全提取我要找的东西。有什么建议吗?你知道吗


Tags: debugimporttypeparsed元组tupleintoneighbor
1条回答
网友
1楼 · 发布于 2024-03-28 15:25:46

好吧,这不是正则表达式,只是标准的序列方法和切片,但它是有效的,至少对于您提供的数据:

from StringIO import StringIO

data = '''
2012-11-22 08:57:25,232 [P:DEBUG] moteId=245 statusElem=1
2012-11-22 08:57:25,042 [P:DEBUG] parsed into Tuple_IsSync(isSync=1)
2012-11-22 08:57:26,128 [P:DEBUG] parsed into Tuple_ScheduleRow(row=9, slotOffset=9, type=6, shared=0, channelOffset=0, neighbor_type=0, neighbor_bodyH=0, neighbor_bodyL=0, backoffExponent=1, backoff=0, numRx=0, numTx=0, numTxACK=0, lastUsedAsn_4=0, lastUsedAsn_2_3=0, lastUsedAsn_0_1=0, next=7638)
'''

flo = StringIO(data)
mlst = []
for line in flo:
    lst = line.split()

    if 'moteId' in line:
        mote, status = lst[3], lst[4]

    elif 'isSync' in line:
        dt, tm = lst[0], lst[1]
        sync = lst[-1][-9:-1]

    elif 'Tuple_ScheduleRow' in line:
        numRx = lst[15].replace(',', '')
        numTx = lst[16].replace(',', '')
        numTxACK = lst[17].replace(',', '')
        t = dt, tm, mote, status, sync, numRx, numTx, numTxACK
        mlst.append(t)

我用StringIO来模拟一个文件,你只需要使用这个文件。最后我将元组存储在主列表中。但是如果你在这么大的文件上这么做,你可能会后悔,这取决于你的记忆状况。最好对元组做任何你需要做的事情,然后让它成为gc'd。如果你必须使用regex,那么你仍然可以使用这个逻辑,为每一个行类型应用不同的regex,替换我的切片,等等

这当然不是优化,但希望它会给你一些想法和一些使用。你知道吗

迈克

相关问题 更多 >