Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按模式读取文件_Python_Regex - Fatal编程技术网

Python 按模式读取文件

Python 按模式读取文件,python,regex,Python,Regex,我正在写一个以文件名命名的阅读器。写入正则表达式掩码: def getmatches(datafilelist,regex=None): “”“获取搜索字符串列表+正则表达式。返回匹配对象列表”“” 如果不是正则表达式: regex=re.compile( r”“” (?P[A-Z0-9]{5})#数据文件的频带类型 _[a-z]+#卫星id _d(?P\d{8})#acq日期 _t(?P\d{7})#颗粒开始时间UTC _e\d+#颗粒结束时间UTC _b(?P\d+)#轨道数 _c\d+#

我正在写一个以文件名命名的阅读器。写入正则表达式掩码:


def getmatches(datafilelist,regex=None):
“”“获取搜索字符串列表+正则表达式。返回匹配对象列表”“”
如果不是正则表达式:
regex=re.compile(
r”“”
(?P[A-Z0-9]{5})#数据文件的频带类型
_[a-z]+#卫星id
_d(?P\d{8})#acq日期
_t(?P\d{7})#颗粒开始时间UTC
_e\d+#颗粒结束时间UTC
_b(?P\d+)#轨道数
_c\d+#文件创建日期/时间
_\w+、h5#更多东西
“”,re.X)
返回[datafilelist中文件名的regex.search(filename)]
文件名:SVI01_j01_d20191004_t0717193_e0730075_b00001_c20191004083048126000_ipop_dev.h5


怎么了?

它只是缺少了一些小东西:

(?P<ftype>[A-Z0-9]{5})_[a-z0-9]+_d(?P<date>\d{8})_t(?P<time>\d{7})_e\d+_b(?P<orbit>\d+)_c\d+_\w+\.h5

如果您希望简化/修改/探索表达式,将在的右上面板中进行解释。如果您愿意,还可以在中查看它与一些示例输入的匹配情况


“sat id”应为下划线,后跟小写字母(
[a-z]+
),但在您的示例中,实际值为“_j01”,其中包含数字
import re

regex = r'(?P<ftype>[A-Z0-9]{5})_[a-z0-9]+_d(?P<date>\d{8})_t(?P<time>\d{7})_e\d+_b(?P<orbit>\d+)_c\d+_\w+\.h5'
string = '''
SVI01_j01_d20191004_t0717193_e0730075_b00001_c20191004083048126000_ipop_dev.h5
'''

print(re.findall(regex, string))
[('SVI01', '20191004', '0717193', '00001')]