python刪除字符串中指定字符的方法
最近開始學(xué)機器學(xué)習(xí),學(xué)習(xí)分析垃圾郵件,其中有一部分是要求去除一段字符中的標點符號,查了一下,網(wǎng)上的大多很復(fù)雜例如這樣
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,'》【】')
我一開始用的后面的這個,著實是有點暴力,于是找了查了一下原文檔,發(fā)現(xiàn)python3中完全有更好的方法去實現(xiàn)這樣的功能(似乎是新更新的?不太清楚,我的是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是可以放三個參數(shù)的(以前一直以為只有兩個....)
前兩個參數(shù)是需要一一對應(yīng)進行替換,需要字符串長度相同
第三個參數(shù)是直接替換為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內(nèi)置的標點符號的合集
既然看到了就總結(jié)下
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python 安裝virtualenv和virtualenvwrapper的方法
下面小編就為大家?guī)硪黄猵ython 安裝virtualenv和virtualenvwrapper的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01pytorch中 gpu與gpu、gpu與cpu 在load時相互轉(zhuǎn)化操作
這篇文章主要介紹了pytorch模型載入之gpu和cpu互轉(zhuǎn)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05使用python切片實現(xiàn)二維數(shù)組復(fù)制示例
今天小編就為大家分享一篇使用python切片實現(xiàn)二維數(shù)組復(fù)制示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11Python參數(shù)解析模塊sys、getopt、argparse使用與對比分析
今天小編就為大家分享一篇關(guān)于Python參數(shù)解析模塊sys、getopt、argparse使用與對比分析,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-04-04