您的位置:首页 > 编程语言 > Python开发

【python cookbook】python过滤字符串中不属于指定集合的字符

2012-07-21 18:13 603 查看
#!/usr/bin/python
# -*- coding: utf-8 -*-

#过滤字符串中不属于指定集合的字符

import string

# 生成所有字符的可复用的字符串 它还可以作为一个翻译表 指明无需翻译
allchars = string.maketrans('','')

def makefilter(keep):
"""返回一个函数 此函数接受一个字符串为参数
并返回字符串的一个部分拷贝
次拷贝纸包含在keep中的字符 keep必须是一个普通字符"""

#生成一个由所有不再keep中的字符组成的字符串:keep的补集 即要删除的字符串
delchars= allchars.translate(allchars,keep)
#生成并返回需要过滤的函数(作为闭包)

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

if __name__ == '__main__':
just_vowels = makefilter('aeiouy')
print just_vowels('four score and seven years ago')


输出 ouoeaeeyeaao

但此代码的缺陷为只适用于普通字符 对于unicode字符不适用

unicode字符串的translate方法只需要一个参数 (一个序列活着一个映射) 并且根据字符串的码值进行索引

码值不是映射的键的字符会直接复制,不做改变

与每个字符对应的值必须是一个unicode字符串或者None

但这种方法对普通字符串不适用

******************************************以下为unicode版代码

通常 使用dict 或着list 作为unicode 字符串的translate 方法参数,来翻译或者删除某些字符

但我们可以使用更好的办法 --编写一个简单的实现

__getitem__(进行索引时会调用的特殊方法)方法的类


import sets
class Keeper(obj):
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)
makefilter = Keeper

if __name__ == '__main__':
just_vowels = makefilter('aeiouy')
print just_vowels(u'four score and seven years ago')


首先使用__init__初始化keep

最后使用__call__回调即

u'four score and seven years ago'.translate(['a','e','i','o','u','y'])


map用法

map(function, iterable, ...)

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

将函数func作用于给定序列的每个元素,并用一个列表来提供返回值;如果func为None,func表现为身份函数,返回一个含有每个序列中元素集合的n个元组的列表。

例如

>>> ls = [1,2,3,4]
>>> print map(lambda x:x*3,ls)
[3, 6, 9, 12]


ord() jie接受长度为一的unicode字符串为参数 返回unicode码值

>>> print ord('a')
97


"双下划线" 开始的是私有成员,意思是只有类对象自己能访问,连子类对象也不能访问到这个数据。

__init__


__init__
方法在类的一个对象被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的 初始化 。注意,这个名称的开始和结尾都是双下划线。

__call__

Python中有一个有趣的语法,只要定义类型的时候,实现__call__函数,这个类型就成为可调用的。

换句话说,我们可以把这个类型的对象当作函数来使用,相当于 重载了括号运算符。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐