当前位置:网站首页>《Python Cookbook 3rd》笔记(2.3):用Shell通配符匹配字符串
《Python Cookbook 3rd》笔记(2.3):用Shell通配符匹配字符串
2020-11-10 10:51:00 【巨輪】
用 Shell 通配符匹配字符串
问题
你想使用 Unix Shell 中常用的通配符 (比如 *.py , Dat[0-9]*.csv 等) 去匹配文本字符串
解法
fnmatch 模块提供了两个函数—— fnmatch() 和 fnmatchcase() ,可以用来实现这样的匹配。用法如下:
>>> 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() 函数使用底层操作系统的大小写敏感规则 (不同的系统是不一样的) 来匹配模式。比如:
>>> # On OS X (Mac)
>>> fnmatch('foo.txt', '*.TXT')
False
>>> # On Windows
>>> fnmatch('foo.txt', '*.TXT')
True
>>>
如果你对这个区别很在意,可以使用 fnmatchcase() 来代替。它完全使用你的模式大小写匹配。比如:
>>> fnmatchcase('foo.txt', '*.TXT')
False
>>>
这两个函数通常会被忽略的一个特性是在处理非文件名的字符串时候它们也是很有用的。比如,假设你有一个街道地址的列表数据:
addresses = [
'5412 N CLARK ST',
'1060 W ADDISON ST',
'1039 W GRANVILLE AVE',
'2122 N CLARK ST',
'4802 N BROADWAY'
]
你可以像这样写列表推导:
>>> 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']
>>>
讨论
fnmatch() 函数匹配能力介于简单的字符串方法和强大的正则表达式之间。如果在数据处理操作中只需要简单的通配符就能完成的时候,这通常是一个比较合理的方案。
版权声明
本文为[巨輪]所创,转载请带上原文链接,感谢
https://my.oschina.net/jallenkwong/blog/4710735
边栏推荐
- CSDN bug5: to be added
- 图-无向图
- Looking for a small immutable dictionary with better performance
- 从零开始学习 YoMo 系列教程:开篇
- 区块链论文集【三十一】
- csdn bug6:待加
- 中央重点布局:未来 5 年,科技自立自强为先,这些行业被点名
- What does the mremote variable in servicemanagerproxy refer to?
- GNU assembly basic mathematical equations multiplication
- B. protocal has 7000eth assets in one week!
猜你喜欢
随机推荐
File初相识
After seven years of pursuing, nearly one billion US dollars of bitcoin was eventually confiscated and confiscated by the US government
工厂方法模式
Graph undirected graph
LeetCode:数组(一)
learning to Estimate 3D Hand Pose from Single RGB Images论文理解
nodejs 个人学习笔记(imook)pm2
csdn bug10:待加
csdn bug11:待加
Oschina: my green plants are potatoes, ginger and garlic
安卓快速关机APP
SEO界,值得收藏的10条金玉良言有哪些?
坚持追查7年,近10亿美元比特币终被美国政府没收充公
区块链论文集【三十一】
selenium webdriver使用click一直失效问题的几种解决方法
JMeter interface test -- a solution with token
用python猜测一个数字是集合里面哪些数字相加求和而来的
2020-11-07
Overview of the most complete anomaly detection algorithm in history
CentOS7本地源yum配置


