当前位置:网站首页>《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
边栏推荐
- Collection of blockchain theory [31]
- [paper reading notes] network embedding with attribute refinement
- csdn bug4:待加
- Graph undirected graph
- GNU assembly language uses inline assembly to extend ASM
- Yixian e-commerce prospectus of perfect diary parent company: focusing on marketing and ignoring R & D, with a loss of 1.1 billion in the first three quarters
- Factory approach model
- Leetcode 1-sum of two numbers
- 编码风格:Mvc模式下SSM环境,代码分层管理
- gnu汇编-基本数学方程-乘法
猜你喜欢
随机推荐
小度“破圈”提速,IoT迎来新故事
CSDN bug7: to be added
【CCPC】2020CCPC长春 F - Strange Memory | 树上启发式合并(dsu on a tree)、主席树
为什么要谨慎使用Arrays.asList、ArrayList的subList?
Connection to XXX could not be established. Broker may not be available
如何看待阿里云成立新零售事业部?
Swoole v4.5.7 版本发布,新增--enable-swoole-json编译选项
[paper reading notes] community oriented attributed network embedding
Thinking about competitive programming: myths and shocking facts
【iOS】苹果登录Sign in with Apple
Graph undirected graph
区块链论文集【三十一】
[paper reading notes] large scale heterogeneous feature embedding
从零开始学习 YoMo 系列教程:开篇
【操作教程 】国标GB28181协议安防视频平台EasyGBS订阅功能介绍及开启步骤
csdn bug9:待加
浅谈字节最新开源联邦机器学习平台Fedlearner
layer.prompt(options, yes) - 输入层
What's the difference between delete, truncate, and drop, and what to do if you delete data by mistake
csdn bug1:待加