您好,欢迎访问一九零五行业门户网

Python 过滤字符串的技巧

python中的map函数非常有用,在字符转换和字符遍历两节都出现过,现在,它又出现了,会给我们带来什么样的惊喜呢?是不是要告诉我们,map是非常棒的,以后要多找它玩呢?
具体的实例
我们需要在目录中遍历,包括子目录(哈哈),找出所有后缀为:rmvb ,avi ,pmp 的文件。(天哪?!你要干什么?这可是我的隐私啊~~)
代码如下:
import os def anytrue(predicate, sequence): return true in map(predicate, sequence) def filterfiles(folder, exts): for filename in os.listdir(folder): if os.path.isdir(folder + '/' + filename): filterfiles(folder + '/' + filename, exts) elif anytrue(filename.endswith, exts): print filename exts = ['.rmvb', '.avi', '.pmp'] filterfiles('/media/personal/movie', exts)
输出结果
来看看有什么好东东:
[66影视www.66ys.cn]迷失第四季04.rmvb
[迷失.第4季].lost.s04e00.rmvb
[迷失lost第四季][第02集][中文字幕].rmvb
《迷失lost第四季》第05集[中文字幕].rmvb
《迷失lost第四季》第06集[中文字幕].rmvb
《迷失lost第四季》第07集[中文字幕].rmvb
天赐第2季01.rmvb
天赐第2季02.rmvb
天赐第2季03.rmvb
天赐第2季04.rmvb
天赐第2季05.rmvb
影视帝国(bbs.cnxp.com).美丽心灵.a.beautiful.mind.2001.cd1.rmvb
( ... 太多了,不要全输出来吧~~)
扩展
cookbook一书中,提供的是itertools.imap来实现对字符串的过滤。imap和map不同的是,imap返回的是一个iteration对象,而map返回的是一个list对象。代码如下:
import itertools def anytrue(predicate, sequence): return true in itertools.imap(predicate, sequence) def endswith(s, *endings): return anytrue(s.endswith, endings) imap 等价于: def imap(function, *iterables): iterables = map(iter, iterables) while true: args = [i.next() for i in iterables] if function is none: yield tuple(args) else: yield function(*args)
以上就是python 过滤字符串的技巧的详细内容。
其它类似信息

推荐信息