python字符串中删除一个字符,python删除某个字符
最近开始学习机器,学习了垃圾邮件的分析。 其中一部分要求消除文字标点符号。 查了一下,网上很多很复杂。 例如,这样
导入模板='想做/兼_职/学生_/的,加,我Q: 1 5. 8 0. 8 ) 6。 0. 2。 3是的,惊喜,啊' temp=temp.decode(UTF8 ) ) string=re.sub([\s\.\"! 3/_,$%^*33330|[——!@#%……* (() ) (.decode )、) (.decode )、temp )打印字符串或其他类似的
' ' ' string模块' ' '导入字符串' ' '的导入标点常量' ' ' string.punctuationtext='*/@'--【】-12 (()测试* ) ) ) 部署string模块sign text=string.punctuation newsign #部署英语符号常量,可添加自定义字符,默认为空signrepl='@'* 引入len (签名文本)符号列表长度的替换字符sign table=str.maketrans (sign text,signrepl ) )生成替换字符表return text.trans LANs ' ' # # ') ) )我第一次使用后的这个,真的很暴力,所以我查了一下原始文档,发现python3有更好的方法来实现这种功能。 ) )像是新的吗? 我不太清楚,我的是python的最新版本3.6.6 )
与上述方法相同,使用了str的translate (和maketrans )
translate()自然不用说这里的重点是maketrans(),先放上官方的文档
staticstr.maketrans(x[,y[,z] ) This static method returns a
translationtableusableforstr.translate (。
If there is only one argument,it must be a dictionary mapping
统一顺序(integers ) or characters (stringsoflength1) to
Unicode ordinals,strings(ofarbitrarylengths ) or None. Character
keyswillthenbeconvertedtoordinals。
If there are two arguments,they must be strings of equal length,
and in the resulting dictionary,each character in x will be mapped
tothecharacteratthesamepositioniny.ifthereisathird
argument,it must be a string,whosecharacterswillbemappedtonone
在内结果。
可以看到maketrans可以包含三个参数(以前以为只有两个……)。
前两个参数必须一对一替换,并且字符串长度必须相同
第三个参数是直接用None替换
这里直接坐代码
import stringi='Hello,how are you!' I.translate(str.maketrans ('、'、'、string.punctuation ) )、hello how are you ' I=' helloworldiamli ' I.translation
既然看到了就总结一下