問題
使用 Unix Shell 中常用的通配符(比如 .py , Dat[0-9].csv 等)去匹配文本字符串
解決方案
fnmatch 模塊提供了兩個(gè)函數(shù)—— fnmatch() 和 fnmatchcase(),可以實(shí)現(xiàn)這樣的匹配。用法如下:
from fnmatch import fnmatch, fnmatchcase
print(fnmatch('foo.txt', '*.txt'))
print(fnmatch('foo.txt', '?oo.txt'))
print(fnmatch('Dat45.csv', 'Dat[0-9]*'))
True
True
True
names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py']
fn = [name for name in names if fnmatch(name, 'Dat*.csv')]
print(fn)
['Dat1.csv', 'Dat2.csv']
fnmatch() 函數(shù)使用底層操作系統(tǒng)的大小寫敏感規(guī)則進(jìn)行匹配,不同的操作系統(tǒng)不一樣。比如:
# On OS X (Mac)
fnmatch('foo.txt', '*.TXT') # returen False
# On Windows
fnmatch('foo.txt', '*.TXT') # return True
如果對(duì)大小寫匹配的區(qū)別很在意,可以使用 fnmatchcase() 來代替,該函數(shù)完全按區(qū)別大小寫匹配。比如:
print(fnmatchcase('foo.txt', '*.TXT'))
False
討論
fnmatch() 函數(shù)匹配能力介于簡(jiǎn)單的字符串方法和強(qiáng)大的正則表達(dá)式之間。 如果在數(shù)據(jù)處理操作中只需要簡(jiǎn)單的通配符就能完成的時(shí)候,這通常是一個(gè)比較合理的方案。
如果代碼需要做文件名的匹配,最好使用 glob 模塊。