当前位置:网站首页>Notes on Python cookbook 3rd (2.3): matching strings with shell wildcards

Notes on Python cookbook 3rd (2.3): matching strings with shell wildcards

2020-11-10 10:51:00 Giant ship

use Shell Wildcards match strings

problem

You want to use Unix Shell The common wildcard in ( such as *.py , Dat[0-9]*.csv etc. ) To match text strings

solution

fnmatch Module provides two functions —— fnmatch() and fnmatchcase() , Can be used to achieve such a match . Usage is as follows :

>>> from fnmatch import fnmatch, fnmatchcase
>>> fnmatch('foo.txt', '*.txt')
True
>>> fnmatch('foo.txt', '?oo.txt')
True
>>> fnmatch('Dat45.csv', 'Dat[0-9]*')
True
>>> names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py']
>>> [name for name in names if fnmatch(name, 'Dat*.csv')]
['Dat1.csv', 'Dat2.csv']
>>>

fnmatch() Function uses the case sensitive rules of the underlying operating system ( Different systems are different ) To match patterns . such as :

>>> # On OS X (Mac)
>>> fnmatch('foo.txt', '*.TXT')
False
>>> # On Windows
>>> fnmatch('foo.txt', '*.TXT')
True
>>>

If you care about the difference , have access to fnmatchcase() Instead of . It completely uses your pattern case matching . such as :

>>> fnmatchcase('foo.txt', '*.TXT')
False
>>>

One of the features that are often overlooked in these two functions is that they are also useful when dealing with non file name strings . such as , Suppose you have a list of street addresses :

addresses = [
	'5412 N CLARK ST',
	'1060 W ADDISON ST',
	'1039 W GRANVILLE AVE',
	'2122 N CLARK ST',
	'4802 N BROADWAY'
]

You can write list derivation like this :

>>> from fnmatch import fnmatchcase
>>> [addr for addr in addresses if fnmatchcase(addr, '* ST')]
['5412 N CLARK ST', '1060 W ADDISON ST', '2122 N CLARK ST']
>>> [addr for addr in addresses if fnmatchcase(addr, '54[0-9][0-9] *CLARK*')]
['5412 N CLARK ST']
>>>

Discuss

fnmatch() Function matching is between simple string methods and powerful regular expressions . If you only need a simple wildcard to complete the data processing operation , This is usually a reasonable plan .

版权声明
本文为[Giant ship]所创,转载请带上原文链接,感谢