Home  >  Article  >  Backend Development  >  Python tips for filtering strings

Python tips for filtering strings

巴扎黑
巴扎黑Original
2017-05-21 18:52:212890browse

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)

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)

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!

Statement:
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