我正在嘗試制作一個快速腳本來簡化一些無聊的會計。基本上我有一個檔案夾,里面裝滿了名稱類似于下面串列中包含的檔案的檔案夾。
我需要按照前幾個檔案名中的指示重命名檔案。
我對如何做到這一點有一個清晰的想法,并且正在撰寫一個快速腳本來完成它。但我遇到了一個愚蠢的問題。我想使用串列理解來獲取日期串列,如最后一行所示。理想情況下,我想做的是:
[re.search(date_pattern, file).match for file in list_of_reciepts]
但這在缺少日期欄位的檔案名上失敗。
關于一個漂亮的整潔替代品的任何想法?
import re
list_of_reciepts = [
'2021-10-18 1.pdf',
'2021-10-18 2.pdf',
'2021-10-18 3.pdf',
'Financial History - Linkt.pdf',
'Scan from 2021-10-04 05_14_16 PM.pdf',
'Scan from 2021-10-07 11_41_26 AM.pdf',
'Scan from 2021-10-19 05_13_22 PM.pdf',
]
date_pattern = re.compile(r'\d{4}-\d{2}-\d{2}')
[re.search(date_pattern, file) for file in list_of_reciepts]
>>>[<re.Match object; span=(0, 10), match='2021-10-18'>,
<re.Match object; span=(0, 10), match='2021-10-18'>,
<re.Match object; span=(0, 10), match='2021-10-18'>,
None,
<re.Match object; span=(10, 20), match='2021-10-04'>,
<re.Match object; span=(10, 20), match='2021-10-07'>,
<re.Match object; span=(10, 20), match='2021-10-19'>]
uj5u.com熱心網友回復:
如果您使用 Python >= 3.8,則可以使用 walrus 運算子:
>>> [sre.group() for file in list_of_reciepts
if (sre := re.search(date_pattern, file))]
['2021-10-18',
'2021-10-18',
'2021-10-18',
'2021-10-04',
'2021-10-07',
'2021-10-19']
對于 Python < 3.8,使用雙重理解:
>>> [sre.group() for sre in [re.search(date_pattern, file)
for file in list_of_reciepts] if sre]
['2021-10-18',
'2021-10-18',
'2021-10-18',
'2021-10-04',
'2021-10-07',
'2021-10-19']
如果你想保留None:
>>> [sre.group() if (sre := re.search(date_pattern, file)) else None
for file in list_of_reciepts]
['2021-10-18',
'2021-10-18',
'2021-10-18',
None,
'2021-10-04',
'2021-10-07',
'2021-10-19']
uj5u.com熱心網友回復:
使用海象運算子
res = [x.group() if (x := re.search(date_pattern, file)) else None for file in list_of_reciepts]
print(res)
輸出
['2021-10-18', '2021-10-18', '2021-10-18', None, '2021-10-04', '2021-10-07', '2021-10-19']
作為替代方案,由于您正在編譯正則運算式,您可以使用map如下:
res = [match.group() if match else match for match in map(date_pattern.search, list_of_reciepts)]
uj5u.com熱心網友回復:
getattr與使用帶條件的賦值運算式相比,您可以使用更簡潔、更短的方法:
import re
v = ['2021-10-18 1.pdf', '2021-10-18 2.pdf', '2021-10-18 3.pdf', 'Financial History - Linkt.pdf', 'Scan from 2021-10-04 05_14_16 PM.pdf', 'Scan from 2021-10-07 11_41_26 AM.pdf', 'Scan from 2021-10-19 05_13_22 PM.pdf']
p = re.compile(r'\d{4}-\d{2}-\d{2}')
r = [getattr(re.search(p, i), 'group', lambda :None)() for i in v]
輸出:
['2021-10-18', '2021-10-18', '2021-10-18', None, '2021-10-04', '2021-10-07', '2021-10-19']
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/343220.html
