Recipe 1.10. Filtering a String for a Set of Characters(Python Cookbook)
1 >>> import string
2 >>> allchars = string.maketrans('', '')
3 >>> def makefilter(keep):
4 delchars = allchars.translate(allchars, keep)
5 def thefilter(s):
6 return s.translate(allchars, delchars)
7 return thefilter
8
9 >>> just_vowels = makefilter('aeiouy')
10 >>> print just_vowels('four score and seven years ago')
11 ouoeaeeyeaao
12 >>> print just_vowels('Hello Ray Zhang')
13 eoaya
14
15 >>> import sets
16 >>> class Keeper():
17 def __init__(self, keep):
18 self.keep = sets.Set(map(ord, keep))
19 def __getitem__(self, n):
20 if n not in self.keep:
21 return None
22 return unichr(n)
23 def __call__(self, s):
24 return unicode(s).translate(self)
25
26 >>> makefilter = Keeper
27 >>> just_vowels = makefilter('aeiouy')
28 >>> print just_vowels(u'four score and seven years ago')
29 ouoeaeeyeaao
30 >>> print just_vowels(u'Hello Ray Zhang')
31 eoaya
32
2 >>> allchars = string.maketrans('', '')
3 >>> def makefilter(keep):
4 delchars = allchars.translate(allchars, keep)
5 def thefilter(s):
6 return s.translate(allchars, delchars)
7 return thefilter
8
9 >>> just_vowels = makefilter('aeiouy')
10 >>> print just_vowels('four score and seven years ago')
11 ouoeaeeyeaao
12 >>> print just_vowels('Hello Ray Zhang')
13 eoaya
14
15 >>> import sets
16 >>> class Keeper():
17 def __init__(self, keep):
18 self.keep = sets.Set(map(ord, keep))
19 def __getitem__(self, n):
20 if n not in self.keep:
21 return None
22 return unichr(n)
23 def __call__(self, s):
24 return unicode(s).translate(self)
25
26 >>> makefilter = Keeper
27 >>> just_vowels = makefilter('aeiouy')
28 >>> print just_vowels(u'four score and seven years ago')
29 ouoeaeeyeaao
30 >>> print just_vowels(u'Hello Ray Zhang')
31 eoaya
32