国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python刪除字符串中指定字符的方法

2020-01-04 14:56:09
字體:
來源:轉載
供稿:網友

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

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.punctuationtext = "*/@》--【】--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 stringi = '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內置的標點符號的合集

既然看到了就總結下

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 泰兴市| 双峰县| 萝北县| 花莲县| 庆元县| 阿拉善盟| 永吉县| 本溪市| 炎陵县| 灯塔市| 清原| 金沙县| 西吉县| 淮阳县| 吐鲁番市| 泾阳县| 喜德县| 临城县| 平湖市| 兴山县| 泸溪县| 泾源县| 望谟县| 启东市| 栾川县| 荔波县| 潞城市| 榆中县| 崇礼县| 梁平县| 曲沃县| 岱山县| 绵竹市| 梁平县| 安图县| 永平县| 略阳县| 永川市| 永安市| 宣汉县| 新干县|