【python cookbook】【字符串与文本】3.利用shell通配符做字符串匹配

时间:2023-03-09 15:22:08
【python cookbook】【字符串与文本】3.利用shell通配符做字符串匹配

问题:当工作在Linux shell下时,使用常见的通配符模式(即,*.py、Dat[0-9]*.csv等)来对文本做匹配

解决方案:fnmatch模块提供的两个函数fnmatch()、fnmatchcase()

#fnmatch()的匹配模式所采用的大小写区分规则和底层文件系统相同(根据操作系统的不同 而不同)

#fnmatchcase()的匹配模式区分大小写

>>> from fnmatch import fnmatch,fnmatchcase
>>> fnmatch('foo.txt','.txt')
False
>>> fnmatch('foo.txt','*.txt')
True
>>> fnmatch('foo.txt','?oo.txt')
True
>>> fnmatch('Dat34.csv','Dat[0-9]*')
True
>>> names=['Dat34.csv','Dat1.csv','config.ini','foo.py']
>>> [name for name in names if fnmatch(name,'Dat*.csv')]
['Dat34.csv', 'Dat1.csv']
>>>
>>> fnmatch('foo.txt','*.TXT')#ON WINDOWS 大写字母匹配
True
>>> fnmatchcase('foo.txt','*.TXT')#on windows大写字母匹配
False
>>>
>>> fnmatch('foo.txt','*.TXT')#ON OS X(Mac) 大写字母匹配
False
>>>

这些函数一个潜在的用途,是它们处理非文件名式的字符串时的特性

# example.py
#
# Example of using shell-wildcard style matching in list comprehensions from fnmatch import fnmatchcase as match addresses = [
'5412 N CLARK ST',
'1060 W ADDISON ST',
'1039 W GRANVILLE AVE',
'2122 N CLARK ST',
'4802 N BROADWAY',
] a = [addr for addr in addresses if match(addr, '* ST')]
print(a) b = [addr for addr in addresses if match(addr, '54[0-9][0-9] *CLARK*')]
print(b)
>>> ================================ RESTART ================================
>>>
['5412 N CLARK ST', '1060 W ADDISON ST', '2122 N CLARK ST']
['5412 N CLARK ST']
>>>

实际上是想编写匹配文件名的代码,应该使用glob模块来完成。