Python正则表达式搜索和分组

2024-04-24 06:45:21 发布

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

04:38:06.151 [http-bio-5443-exec-8] INFO  A.g.r.q.r.flex.RubixService   - [NO-ID] [Mar 26, 2014 04:38:06 UTC] -     [5a-y2-24C363B223F1CB534B8DCA5693ADF2E9] --0->servAggregateMultiple:61224380032:[[{"responseMeasures":    ["SubscriberCnt","UpBytes","DownBytes","SessionCount","SubscriberPercentage","UpBytesPercentage","DownBytesPercentage","SessionCountPercentage"]
"sortProperty":"SubscriberCnt"

我有一个文本文件中的数据。我想执行搜索并找到响应度量,就是有这一块数据。如果它找到了,我想把之后的一切都存储起来,那就是:-

["SubscriberCnt","UpBytes","DownBytes","SessionCount","SubscriberPercentage","UpBytesPercentage","DownBytesPercentage","SessionCountPercentage"]

我想把它作为一个组存储在一个变量中。类似地,我希望找到sortProperty并将“SubscriberCnt”作为一个组存储在变量中

这是我的密码snippet:- 你知道吗

import re
fo = open("data.txt", "r")
data = fo.readlines()
for n in data:
        matchMeasure = re.search("responseMeasures:", n)
        if matchMeasure:
                measureData =  matchMeasure.groups()
                print "Measures are" +  str(measureData)
        matchDimension = re.search("sortProperty", n)
        if matchSort:
                sortData = matchSort.groups()
                print "Group by" + str(sortData)

这段代码可能不是最好的方式来做这件事,但只是为了显示我正在寻找什么

预期输出Iwant:- 你知道吗

Meausres are:-
SubscriberCnt
UpBytes
DownBytes
SessionCount
SubscriberPercentage
UpBytesPercentage
DownBytesPercentage
SessionCountPercentage"
Group by SubscriberCnt

Tags: 数据redatafosessioncountsortpropertymatchmeasureupbytes
1条回答
网友
1楼 · 发布于 2024-04-24 06:45:21

您可以通过使用re.findall来实现这一点

with open('data.txt','r') as f:

    first_filter = re.findall(r"[\w']+", f.read())
    measures = first_filter[first_filter.index('responseMeasures')+1:first_filter.index('sortProperty')]
    sortby = first_filter[first_filter.index('sortProperty')+1::]

    for measure in measures:
        print measure

    print "Group by:"

    for sort_type in sortby:
        print sort_type

相关问题 更多 >