如何从文件对象(data.txt)中提取此正则表达式中的组?
import numpy as np
import re
import os
ifile = open("data.txt",'r')
# Regex pattern
pattern = re.compile(r"""
^Time:(\d{2}:\d{2}:\d{2}) # Time: 12:34:56 at beginning of line
\r{2} # Two carriage return
\D+ # 1 or more non-digits
storeU=(\d+\.\d+)
\s
uIx=(\d+)
\s
storeI=(-?\d+.\d+)
\s
iIx=(\d+)
\s
avgCI=(-?\d+.\d+)
""", re.VERBOSE | re.MULTILINE)
time = [];
for line in ifile:
match = re.search(pattern, line)
if match:
time.append(match.group(1))
Run Code Online (Sandbox Code Playgroud)
代码的最后一部分的问题是我逐行迭代,这显然不适用于多行正则表达式.我试过这样用pattern.finditer(ifile):
for match in pattern.finditer(ifile):
print match
Run Code Online (Sandbox Code Playgroud)
...只是为了查看它是否有效,但是finditer方法需要一个字符串或缓冲区.
我也试过这种方法,但无法让它起作用
matches = [m.groups() for m …Run Code Online (Sandbox Code Playgroud)