在Python中通过正则表达式提取重复
我试图从通过正则表达式给出的大量数据中提取一些有用的数据。在Python中通过正则表达式提取重复,python,regex,pattern-matching,Python,Regex,Pattern Matching,我试图从通过正则表达式给出的大量数据中提取一些有用的数据。 示例字符串: test 1: hello op1 yviphf hello op2 vipqwe test 2: hello op3 hello op4 vipgt hello op5 zcv 上面包含2个测试编号,但有几个。我想提取op1、op2、op3、op4、op5以及相应的测试编号。每次测试中op的数量可能会有所不同。 以下是我尝试编写的模式,但没有帮助: test\s(\d+).*?(?:hello\s+(\S+).*?\n
示例字符串:
test 1:
hello op1 yviphf
hello op2 vipqwe
test 2:
hello op3
hello op4 vipgt
hello op5 zcv
上面包含2个测试编号,但有几个。我想提取op1、op2、op3、op4、op5以及相应的测试编号。每次测试中op的数量可能会有所不同。以下是我尝试编写的模式,但没有帮助:
test\s(\d+).*?(?:hello\s+(\S+).*?\n)+
输出可以是列表的列表。主列表将第一个元素作为测试编号,第二个元素可能是包含所有op的列表。我建议基于正则表达式的三步方法
- 首先,使用
和r'test\s*(\d+)
获取所有测试编号(这将仅获取编号列表,因为re.findall
子模式位于捕获组中)\d+
- 其次,使用
regex拆分输入字符串,以获得带有test\s*\d+
代码的子部分,并在每个非空块上运行hello
(或hello\s+(\s+)
(如果(?m)^hello\s*(\s+)
从行开始)regex(同样,hello
将只获取包含在捕获组中的re.findall
子匹配)\S+
- 将列表合并到元组列表中
结果:
[('1',['op1','op2']),('2',['op3','op4','op5'])]
您需要使用正则表达式吗
如果没有,则可以使用循环、strin比较和拆分:
data = {}
key = '_'
for linea in text.split('\n'):
if "test" in linea:
key = linea.split()[1][:-1]
data[key]=[]
else:
_data_ = linea.split()[1]
data[key].append(_data_)
print data
> {'1': ['op1', 'op2'], '2': ['op3', 'op4', 'op5']}
分两步进行:首先匹配完整的部分,然后为每个部分匹配op值。您需要使用正则表达式吗?您正在寻找
/s
标志吗?请参阅“可以”标记。您应该给出一个更好的示例字符串(更现实),因为很难回答。(ops看起来如何,每行的开头是否都有“hello”一词?)。如果您有大量数据,逐行工作会更好,也许您可以避免使用正则表达式并获得更快的结果。
data = {}
key = '_'
for linea in text.split('\n'):
if "test" in linea:
key = linea.split()[1][:-1]
data[key]=[]
else:
_data_ = linea.split()[1]
data[key].append(_data_)
print data
> {'1': ['op1', 'op2'], '2': ['op3', 'op4', 'op5']}