1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 问题解决:Python | 字符串去除(中文 英文 数字 标点符号)

问题解决:Python | 字符串去除(中文 英文 数字 标点符号)

时间:2024-05-04 05:46:00

相关推荐

问题解决:Python | 字符串去除(中文 英文 数字 标点符号)

去除英文标点符号

string.punctuation包含所有英文标点符号

'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

import stringstring.punctuationtext = "Don't worry, be happy!" # 'Don\'t worry, be happy'punctuation_string = string.punctuationfor i in punctuation_string:text = text.replace(i, '')print(text)'''Dont worry be happy'''

import rere.sub('[{}]'.format(punctuation_string),"",text)''''Dont worry be happy''''

去除中文标点符号

调用zhon包的zhon.hanzi.punctuation函数即可得到中文的标点符号集合。

'"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、\u3000、〃〈〉《》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟 〰〾〿–—‘’‛“”„‟…‧﹏﹑﹔·!?。。'

from zhon.hanzi import punctuationpunctuationtext = '生活就像【】,如果##'punctuation_str = punctuationfor i in punctuation_str:text = text.replace(i, '')print(text)''''生活就像如果''''

import rere.sub('[{}]'.format(punctuation),"",text)''''生活就像如果''''

去除中文

import retext = '生活就像【】,如果##'temp = re.sub('[\u4e00-\u9fa5]','',text)print(temp)''''【】,##''''

from zhon.hanzi import charactersimport re text = '生活就像【】,如果##'temp = re.sub('[{}]'.format(characters),'',text)print(temp)''''【】,##''''

去除英文

import retext = "aksjn ekljfk # ! len223"temp = re.sub('[a-zA-Z]','',text)print(temp)'''' # ! 223''''

去除数字

其实对于\d \s \w这些,小写是数字\空格\数字字母,大写即是非数字\非空格\非数字字母,可以合理运用~

import retext="哈aksjn ekljfk # ! len223"temp = re.sub('[\d]','',text) # [0-9]print(temp)''''哈aksjn ekljfk # ! len''''

去除空格

有很多方法,比如:Python 字符串去除空格的方法

import retext="aksjn ekljfk # ! len223"temp = re.sub('[\s]','',text) #temp = text.strip()print(temp)''''aksjn ekljfk # ! len223''''

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。