12

如何从文件对象(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))

代码最后一部分的问题是我逐行迭代,这显然不适用于多行正则表达式。我试过这样使用pattern.finditer(ifile)

for match in pattern.finditer(ifile):
    print match

...只是看看它是否有效,但 finditer 方法需要一个字符串或缓冲区。

我也尝试过这种方法,但无法正常工作

matches = [m.groups() for m in pattern.finditer(ifile)]

任何想法?


在 Mike 和 Tuomas 发表评论后,我被告知使用 .read().. 类似这样的东西:

ifile = open("data.txt",'r').read()

这工作正常,但这是搜索文件的正确方法吗?不能让它工作...

for i in pattern.finditer(ifile):
    match = re.search(pattern, i)
    if match:
        time.append(match.group(1))

解决方案

# Open file as file object and read to string
ifile = open("data.txt",'r')

# Read file object to string
text = ifile.read()

# Close file object
ifile.close()

# Regex pattern
pattern_meas = re.compile(r"""
                ^Time:(\d{2}:\d{2}:\d{2})   # Time: 12:34:56 at beginning of line
                \n{2}                       # Two newlines
                \D+                         # 1 or more non-digits
                storeU=(\d+\.\d+)           # Decimal-number
                \s
                uIx=(\d+)                   # Fetch uIx-variable
                \s
                storeI=(-?\d+.\d+)          # Fetch storeI-variable
                \s
                iIx=(\d+)                   # Fetch iIx-variable
                \s
                avgCI=(-?\d+.\d+)           # Fetch avgCI-variable
                """, re.VERBOSE | re.MULTILINE)

file_times = open("output_times.txt","w")
for match in pattern_meas.finditer(text):
    output = "%s,\t%s,\t\t%s,\t%s,\t\t%s,\t%s\n" % (match.group(1), match.group(2), match.group(3), match.group(4), match.group(5), match.group(6))
    file_times.write(output)
file_times.close()

也许它可以写得更紧凑和pythonic......

4

3 回答 3

5

您可以将文件对象中的数据读入字符串ifile.read()

于 2010-03-12T15:18:46.890 回答
2
times = [match.group(1) for match in pattern.finditer(ifile.read())]

finditer产量MatchObjects。如果正则表达式不匹配任何内容times将是一个空列表。

您还可以修改您的正则表达式以对、和使用非捕获组storeU,然后将仅包含匹配的时间。storeIiIxavgCIpattern.findall

注意:命名变量time可能会影响标准库模块。times会是更好的选择。

于 2010-03-12T15:49:51.177 回答
1

为什么不使用将整个文件读入缓冲区

buffer = open("data.txt").read()

然后用那个搜索?

于 2010-03-12T15:20:07.370 回答