首页 > 解决方案 > 如何分配第一场比赛和第二场比赛?

问题描述

我有一条线要拆分:

['Time      : tap/stap_tap2gpsb/SBMSGRSP/status/bit0: 19359560-19359561 step 1', 'Expect    : tap/stap_tap2gpsb/SBMSGRSP/status/bit0: XX', 'Acquired  : tap/stap_tap2gpsb/SBMSGRSP/status/bit0: 00', 'Time      : tap/stap_tap2gpsb/SBMSGRSP/status/bit1: 19359560-19359561 step 1', 'Expect    : tap/stap_tap2gpsb/SBMSGRSP/status/bit1: XX', 'Acquired  : tap/stap_tap2gpsb/SBMSGRSP/status/bit1: 00', '']

我想从以下行中获取某些单词:

Acquired  : tap/stap_tap2gpsb/SBMSGRSP/status/bit0: 00
Acquired  : tap/stap_tap2gpsb/SBMSGRSP/status/bit1: 00

我正在使用 re.search 函数来匹配这些行,我得到了这些:

searchObj.group()  =  Acquired  : tap/stap_tap2gpsb/SBMSGRSP/status/bit0:0
searchObj.group(1) =  0
searchObj.group(2) =  0
status[0] ==  0
searchObj.group()  =  Acquired  : tap/stap_tap2gpsb/SBMSGRSP/status/bit1:0
searchObj.group(1) =  1
searchObj.group(2) =  0
status[1] ==  0

如何将第一场比赛和第二场比赛附加在一起?因为我想要做的是我需要 status[0] 并且 status[1] 给出 1 来传递值,否则它将把这些值扔进失败的值

以下是我的代码:

for line in lines:
    searchObj = re.search(r'^Acquired\s+:tap/stap_tap2gpsb/SBMSGRSP/status/bit(\d): (\d)', str(line))
    if searchObj:
        print "searchObj.group()  = ",  searchObj.group()
        print "searchObj.group(1) = ", searchObj.group(1)
        print "searchObj.group(2) = ", searchObj.group(2)
        print "status[" + searchObj.group(1) + "] ==  " + searchObj.group(2)

标签: python

解决方案


您可以轻松地将匹配项收集到对您有意义的任何数据结构中。例如:

match_lines = []
tap_tuples = []
for line in lines:
    searchObj = re.search(r'^Acquired\s+:tap/stap_tap2gpsb/SBMSGRSP/status/bit(\d): (\d)', str(line))
    if searchObj:
        match_lines.append(line)
        tap_tuples.append((searchObj.group(1), searchObj.group(2)))
print('\n'.join(match_lines))
print(';'.join(tap_tuples))

顺便说一句,如果您从文本文件中获取这些行,您可能希望同时处理它们:

with open('file.txt') as handle:
     for line in handle:
        ...

如果这是在函数内部,yield如果您希望调用代码一个一个地处理它们,那么每次找到匹配项时可能会得到一个结果。对该函数yield的下一次调用将从仍然打开的文件句柄中进行下一次匹配,直到输入文件被使用。


推荐阅读