Python高效去除字符串标点符号:translate与maketrans用法详解
本文介绍Python中利用str.maketrans()与str.translate()高效删除字符串中指定字符(如标点符号)的方法。通过对比正则表达式等复杂方案,详解maketrans三个参数的用法及string.punctuation内置常量,提供简洁代码示例,适用于Python 3环境下的文本清洗任务。
近期在机器学习项目中涉及垃圾邮件分析,其中一项预处理步骤是移除文本中的标点符号。查阅相关资料发现,网上常见的解决方案往往较为繁琐,例如使用正则表达式进行匹配替换。
import re
temp = "司法局让我和户 1 5. 8 0. !!?? 客户维护户外"
temp = temp.decode("utf8")
string = re.sub("[\s+\.\!\/_,$%^*(+\"\']+|[+——!,。?、~@#¥%……&*()]+".decode("utf8"), "".decode("utf8"),temp)
print string
另一种常见做法是通过循环逐个字符判断并剔除,这种方式虽然直观但效率较低,代码显得较为冗长。
'''引入string模块'''
import string
'''使用标点符号常量'''
string.punctuation
text = "*/@》--【】--12()测试*()"
'''去除字符串中所有的字符,可增加自定义字符'''
def strclear(text,newsign=''):
import string # 引入string模块
signtext = string.punctuation + newsign # 引入英文符号常量,可附加自定义字符,默认为空
signrepl = '@'*len(signtext) # 引入符号列表长度的替换字符
signtable = str.maketrans(signtext,signrepl) # 生成替换字符表
return text.translate(signtable).replace('@','') # 最后将替换字符替换为空即可
strclear(text,'》【】')
起初我采用了上述第二种方法,感觉实现方式过于粗暴。随后查阅Python官方文档,发现Python 3提供了更优雅的内置方法来实现此功能(具体是否为新特性尚不明确,本人使用的是Python 3.6.6版本)。
该方法同样依赖于字符串对象的translate()方法,但其核心在于配合使用maketrans()函数。
关于translate()函数的用法此处不再赘述,重点在于解析maketrans()函数。首先参考官方文档说明。
static str.maketrans(x[, y[, z]]) This static method returns a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
从文档可以看出,maketrans()函数支持三个参数(此前一直误以为仅支持两个参数)。
前两个参数用于建立字符的一一对应替换关系,要求这两个参数字符串长度必须相同。
第三个参数用于指定需要直接删除(即映射为None)的字符集合。
下面直接展示具体的代码实现。
import string
i = 'Hello, how are you!'
i.translate(str.maketrans('', '', string.punctuation))
>>>'Hello how are you'
i = 'hello world i am li'
i.translate(str.maketrans('','','l'))
>>>'heo word i am i'
其中string.punctuation是Python内置的包含所有英文标点符号的字符串常量。
基于以上分析,总结如下。
以上内容为本文的全部介绍,希望能为读者的学习提供便利,同时也欢迎大家继续支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









