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

我也是第一次听说,maketrans & translate in python

2010-12-26 14:58 357 查看
http://blog.donews.com/tinylee/archive/2007/06/14/1175344.aspx

Python Cook 1.9 简化使用string的translate方法 需求: 想使用强大的string的translate方法,却困惑于它复杂的用法和参数,也不知道string.maketrans的工作机制 .我们需要的只是简单的使用它们的功能.
讨论: 我们在这里简单实现一个方法工厂,可以处理常用的这一类的问题:
import string
def translator(frm='', to='', delete='', keep=None):
if len(to) == 1:
to = to * len(frm)
trans = string.maketrans(frm, to)
if keep is not None:
allchars = string.maketrans('', '')
delete = allchars.translate(allchars, keep.translate(allchars, delete))
def translate(s):
return s.translate(trans, delete)
return translate

下面是一些translator的用法:

可以只保留需要的字符

>>> digits_only = translator(keep=string.digits)
>>> digits_only('Chris Perkins : 224-7992')
'2247992' 可以过滤指定的字符:

>>> no_digits = translator(delete=string.digits)
>>> no_digits(‘Chris Perkins : 224-7992′)
‘Chris Perkins : -’
可以替换指定的字符:
>>> digits_to_hash = translator(from=string.digits, to=’#')
>>> digits_to_hash(‘Chris Perkins : 224-7992′)
‘Chris Perkins : ###-####’
相关说明:
内部方法,在上面的例子中,我们使用了一个内部方法来实现方法工厂,返回一个变量来表示内部方法,然后接收参数来实现功能.
最简单的方法工厂可以写成下面这个样子:
def make_adder(basenum):
def adder(args):
return args+basenum
return adder
比如我们要做一个以100为基数的加法器,可以这样使用:
base100 = make_addr(100)
print base100(45)
>>>145
讨论中的例子,我们返回了自己定制的translate方法 ,它以我们自己定制的delete为参数,来实现我们的keep需求:
allchars = string.maketrans('', '')

返回了包含所有字符的列表

keep.translate(allchars, delete)
返回了过滤掉删除字符的字符表.
allchars.translate(allchars, keep.translate(allchars, delete))

又做了一次运算,现在剩下的只是要删除的字符了.
如果keep和delete不同时使用,可以这样写:
allchars = string.maketrans('', '')
delete = allchars.translate(allchars, keep)

maketrans(…)
maketrans(frm, to) -> string
Return a translation table (a string of 256 bytes long)
suitable for use in string.translate. The strings frm and to
must be of the same length.
translate(…)
S.translate(table [,deletechars]) -> string
Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256.

if you switch the maketrans from & to may be it’s a simple bi-encription way
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: