我正在使用 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 可以處理這個嗎?如果沒有,還有其他方法可以進行嗎?
uj5u.com熱心網友回復:
您使用的模式不符合您的預期。以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://www.uj5u.com/ruanti/427436.html
標籤:Python python-3.x
