Match multiline regex in file object

前端 未结 3 540
遥遥无期
遥遥无期 2021-01-02 02:22

How can I extract the groups from this regex from a file object (data.txt)?

import numpy as np
import re
import os
ifile = open(\"data.txt\",\'r\')

# Regex          


        
相关标签:
3条回答
  • 2021-01-02 03:11

    You can read the data from the file object into a string with ifile.read()

    0 讨论(0)
  • 2021-01-02 03:21

    Why don't you read the whole file into a buffer using

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

    and then do a search with that?

    0 讨论(0)
  • 2021-01-02 03:27
    times = [match.group(1) for match in pattern.finditer(ifile.read())]
    

    finditer yield MatchObjects. If the regex doesn't match anything times will be an empty list.

    You can also modify your regex to use non-capturing groups for storeU, storeI, iIx and avgCI, then pattern.findall will contain only matched times.

    Note: naming variable time might shadow standard library module. times would be a better option.

    0 讨论(0)
提交回复
热议问题