神剑山庄资源网 Design By www.hcban.com
最近开始学机器学习,学习分析垃圾邮件,其中有一部分是要求去除一段字符中的标点符号,查了一下,网上的大多很复杂例如这样
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,'》【】')
我一开始用的后面的这个,着实是有点暴力,于是找了查了一下原文档,发现python3中完全有更好的方法去实现这样的功能(似乎是新更新的"htmlcode">
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内置的标点符号的合集
既然看到了就总结下
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com
暂无python删除字符串中指定字符的方法的评论...
更新日志
2024年10月02日
2024年10月02日
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】