python - 如何分配第一场比赛和第二场比赛?
问题描述
我有一条线要拆分:
['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)
解决方案
您可以轻松地将匹配项收集到对您有意义的任何数据结构中。例如:
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
的下一次调用将从仍然打开的文件句柄中进行下一次匹配,直到输入文件被使用。
推荐阅读
- algorithm - 使用 while 循环的 F# 阶乘函数
- sql - 如何根据特定文本对列进行分组并使用 ORACLE 数据库对它们进行汇总
- php - Monolog 不接受 Crunz 回调中的严重错误
- c# - Unity Hololens System.web.httputils 在目标框架中不存在
- google-sheets - Google Sheets SUMIFS 带有复选框的不同标准
- r - 如何使用 dplyr 跨 R 中的多个列进行聚合
- rest - WinHttp.WinHttpRequest.5.1 REST API
- typescript - Typescript 元组成员的类型解析 - 为什么会编译?
- php - 在 Wordpress 中创建自定义帖子类型
- javascript - 如何使用 Visual Studio 2019 和 javascript 从 api 获取数据?