python刪除字符串中指定字符


最近開始學機器學習,學習分析垃圾郵件,其中有一部分是要求去除一段字符中的標點符號,查了一下,網上的大多很復雜例如這樣

import re  
temp = "想做/ 兼_職/學生_/ 的 、加,我Q:  1 5.  8 0. !!??  8 6 。0.  2。 3     有,驚,喜,哦"  
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中完全有更好的方法去實現這樣的功能(似乎是新更新的?不太清楚,我的是python最新版本3.6.6)

和上面的方法一樣是利用的是str的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內置的標點符號的合集

既然看到了就總結下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM