Python tips for filtering strings

巴扎黑
Release: 2017-05-21 18:52:21
Original
2880 people have browsed it

The map function in Python is very useful. It has appeared in both the character conversion and character traversal sections. Now, it appears again. What kind of surprises will it bring us? Are you trying to tell us that map is great and we should play with it more in the future?

Specific example
We need to traverse the directory, including subdirectories (haha), and find all files with the suffix: rmvb, avi, pmp. (Oh my God?! What are you doing? This is my privacy~~)

The code is as follows:

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)
Copy after login

Output results
Let’s see what’s good :
[66影视www.66ys.cn] Lost Season 4 04.rmvb
[Lost. Season 4].Lost.S04E00.rmvb
[Lost Season 4][Episode 02 ][Chinese subtitles].rmvb
《Lost Season 4》episode 05[Chinese subtitles].rmvb
《Lost Season 4》episode 06[Chinese subtitles].rmvb
《Lost》 Lost Season 4 Episode 07 [Chinese subtitles].rmvb
天 Ci Season 2 01.rmvb
天 Ci Season 2 02.rmvb
天 Ci Season 2 03.rmvb
天 Ci 2 Season 04.rmvb
天 Ci Season 2 05.rmvb
Film and Television Empire (bbs.cnxp.com). Beautiful Mind.A.Beautiful.Mind.2001.CD1.rmvb
( ... too many No, don’t output everything~~)


Extension
CookBook provides itertools.imap to filter strings. The difference between imap and map is that imap returns an iteration object, while map returns a list object. The code is as follows:

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)
Copy after login

The above is the detailed content of Python tips for filtering strings. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template