Files
Python_CookBook_repo/2.字符串和文本/3.shell通配符做字符串匹配.py

26 lines
932 B
Python
Raw Permalink Normal View History

2025-09-10 16:12:45 +08:00
from fnmatch import fnmatch, fnmatchcase
if __name__ == '__main__':
# 如果想用shell通配符做字符串匹配可以用上面的这两个函数
is_txt = fnmatch("suka.txt", "*.txt")
print(is_txt)
is_txt = fnmatchcase("suka.txt", "??ka.txt")
print(is_txt)
# 注意fnmatchcase不会对输入的name进行大小写标准化而fnmatch会对输入标准化后再进行匹配
# 需要小心的是大小写标准化的模式与底层文件系统相同比如windows不需要区分大小写但是mac要
address = [
'5412 N CLARK ST',
'1060 W ADDISON ST',
'1039 W GRANVILLE AVE',
'2122 N CLARK ST',
'4802 N BROADWAY'
]
# 可以用正则进行筛选
ST = [addr for addr in address if fnmatchcase(addr, "* ST")]
print(ST)
NUM_S = [addr for addr in address if fnmatchcase(addr, '54[0-9][0-9] *CLARK*')]
print(NUM_S)