当前位置: 首页 > 图文教程 > 脚本技术 > Python > Python translator使用实例

Python
wxPython 入门教程
Python日期操作学习笔记
Python函数学习笔记
Python转码问题的解决方法
python sqlobject(mysql)中文乱码解决方法
Python 连连看连接算法
Python类的基础入门知识
Python GAE、Django导出Excel的方法
python 参数列表中的self 显式不等于冗余
下载糗事百科的内容_python版
pymssql ntext字段调用问题解决方法
Python 面向对象 成员的访问约束
python 测试实现方法
python 数据加密代码
python zip文件 压缩
python 文件与目录操作
python3.0 字典key排序
Python 学习笔记
Python Mysql数据库操作 Perl操作Mysql数据库
Python MD5文件生成码

Python translator使用实例


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-11   浏览: 102 ::
收藏到网摘: n/a

translator实例应用代码 1.string.maketrans设置字符串转换规则表(translation table)
复制代码 代码如下:

allchars = string.maketrans('', '')#所有的字符串,即不替换字符串
aTob = string.maketrans('a','b')#将字符a转换为字符b

2.translate函数进行字符串的替换和删除,第一个参数是字符串转换规则表(translation table),第二个参数是要删除的字符串。比如,要将字符串s中的所有e替换为a,同时要删除所有的o
复制代码 代码如下:

aTob = string.maketrans('e','a')
s = 'hello python'
print s.translate(aTob, 'o')

输出结果:
hall pythn

3.假如我们这样使用
复制代码 代码如下:

allchars = string.maketrans('', '')
k = allchars.translate(allchars, 'a')

allchars表示所有的字符串,而k表示从所有的字符串中去除掉字符a,就是说所有的字符,除了a,因此,我们再调用如下方法时:
复制代码 代码如下:

s = 'abc'
print s.translate(allchars, k)

字面意思是,输出“字符串s中除去任何不是字符a的字符",即,只输出字符a,因此输出结果为:
a
4.现在,已经不难理解下面这个函数了
复制代码 代码如下:

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调用:
复制代码 代码如下:

digits_only = translator(keep=string.digits)
print digits_only('Chris Perkins : 224-7992')
digits_to_hash = translator(frm=string.digits, to='#')
print digits_to_hash('Chris Perkins : 224-7992')

输出结果:
2247992
Chris Perkins : ###-####