现在的位置: 首页 > 综合 > 正文

001_010 Python 过滤字符串中不属于指定集合的元素

2018年02月15日 ⁄ 综合 ⁄ 共 736字 ⁄ 字号 评论关闭

代码如下:

#encoding=utf-8

print '中国'

#输出字符串中属于某一个集合的字符 not support unicode
print '不支持unicode'
import string

allchars = string.maketrans('','')

def makefilter(keep):
    delchars = allchars.translate(allchars,keep)
    def thefilter(s):
        return s.translate(allchars,delchars)
    return thefilter

just_aeio = makefilter('aeiouy')
print just_aeio('fouadkjf;laksjdf;lj;lka中国')
#print just_aeio(u'fouadkjf;laksjdf;lj;lka中国') #不能使用

print '支持unicode'
#处理Unicode字符串 上面代码不适用
import sets
class Keeper(object):
    def __init__(self,keep):
        self.keep = sets.Set(map(ord,keep))
    def __getitem__(self,n):
        if n not in self.keep:
            return None
        return unichr(n)
    def __call__(self,s):
        return unicode(s).translate(self)
    
make_keeper = Keeper
ujust_aeio = make_keeper(u'aeiouy国')
print ujust_aeio(u'foadfasa中国')

打印结果如下:

中国
不支持unicode
ouaaa
支持unicode
oaaa国

抱歉!评论已关闭.