我使用parse.parse根据文件名与给定模式匹配的方式查找文件。是否可以在模式中定义特定的表达式宽度来为文件研究添加更多的条件?
让我们假设以下代码:
from parse import parse
patterns = ['file_{city:3w}_{date:6w}', 'file_another_one_{city:3w}_{date:6w}']
def find_and_display_pattern(filename):
print('### searching for file {} ###'.format(filename))
for pattern in patterns:
parse_result = parse(pattern, filename)
if not parse is None:
print('{} pattern found for file {}'.format(pattern, filename))
print('result :')
print(parse_result)
return
find_and_display_pattern('file_PRS_02182022')
find_and_display_pattern('file_another_one_PRS_02182022')我得到以下输出:
### searching for file file_PRS_02182022 ###
file_{city:3w}_{date:6w} pattern found for file file_PRS_02182022
result :
<Result () {'city': 'PRS', 'date': '02182022'}>
### searching for file file_another_one_PARIS_02182022 ###
file_{city:3w}_{date:6w} pattern found for file file_another_one_PRS_02182022
result :
<Result () {'city': 'another_one_PRS', 'date': '02182022'}>文件“file_another_one_PRS_02182022”的问题是,我除了检索第二个模式:'file_another_one_{ city :3w}_{date:6w}‘之外,还有特定表达式宽度(城市为3个字符,日期为6个字符),这将提供以下输出:
### searching for file file_another_one_PRS_02182022 ###
file_another_one_{city:3w}_{date:6w} pattern found for file file_another_one_PRS_02182022
result :
<Result () {'city': 'PRS', 'date': '02182022'}>parse.parse能处理这个问题吗?如果没有的话,还有其他办法吗?
发布于 2022-02-18 13:53:38
您正在使用的模式不做您期望的事情。例如,w类型:
字母、数字和下划线
这意味着任何数字的字母,数字和下划线。但是,对于正则表达式,通配符\w只指示一个字母、数字或下划线:我想这就是您在w前面指定宽度的原因,但完全没有必要。然后,关于宽度和精度:
宽度指定最小大小,精度指定最大值。
在您的例子中,最好的选择是精确性,因为城市最多只有3字符长。如果您需要精确地使用3个字符,那么请同时使用两个字符:3.3。
此外,您在if语句中犯了一个错误:if not parse is None应该是if parse_result is not None。
这是一个改进的版本,它可以满足您的需要,并为日期类型定义了一个自定义解析器 (请参阅自定义类型转换):
from parse import parse, with_pattern
from datetime import datetime
@with_pattern(r'\d{8}')
def parse_date(text):
return datetime.strptime(text, '%m%d%Y').date()
patterns = ['file_{city:3.3}_{date:Date}', 'file_another_one_{city:3.3}_{date:Date}']
def find_and_display_pattern(filename):
print('### searching for file {} ###'.format(filename))
for pattern in patterns:
parse_result = parse(pattern, filename, dict(Date=parse_date))
if parse_result is not None:
print('{} pattern found for file {}'.format(pattern, filename))
print('result :')
print(parse_result)
return
find_and_display_pattern('file_PRS_02182022')
find_and_display_pattern('file_another_one_PRS_02182022')输出:
### searching for file file_PRS_02182022 ###
file_{city:3.3}_{date:Date} pattern found for file file_PRS_02182022
result :
<Result () {'city': 'PRS', 'date': datetime.date(2022, 2, 18)}>
### searching for file file_another_one_PRS_02182022 ###
file_another_one_{city:3.3}_{date:Date} pattern found for file file_another_one_PRS_02182022
result :
<Result () {'city': 'PRS', 'date': datetime.date(2022, 2, 18)}>https://stackoverflow.com/questions/71173860
复制相似问题