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

首頁 > 編程 > Python > 正文

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

2020-02-15 22:43:37
字體:
來源:轉載
供稿:網友

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

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內置的標點符號的合集

既然看到了就總結下

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 青铜峡市| 安徽省| 南部县| 宕昌县| 邵阳县| 东光县| 西城区| 循化| 龙陵县| 蒲城县| 通道| 鄱阳县| 广汉市| 轮台县| 延吉市| 大安市| 桃园县| 宜兰县| 神木县| 万源市| 桃江县| 珲春市| 宁蒗| 商丘市| 姜堰市| 西宁市| 吉安县| 会宁县| 花垣县| 涪陵区| 石棉县| 綦江县| 儋州市| 启东市| 通山县| 集安市| 都兰县| 平乡县| 华容县| 三穗县| 白山市|