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

本文介绍了如何使用Python的string和zhon库来移除文本中的英文和中文标点符号,包括使用replace方法和正则表达式re.sub函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

去除英文标点符号

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

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

text = "Don't worry, be happy!" # 'Don\'t worry, be happy'

punctuation_string = string.punctuation
for i in punctuation_string:
    text = text.replace(i, '')
print(text)

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

'''
'Dont worry be happy'
'''

去除中文标点符号

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

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

text = '生活就像【】,如果##'

punctuation_str = punctuation
for i in punctuation_str:
    text = text.replace(i, '')
print(text)

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

'''
'生活就像如果'
'''

去除中文

import re

text = '生活就像【】,如果##'

temp = re.sub('[\u4e00-\u9fa5]','',text)
print(temp)

'''
'【】,##'
'''
from zhon.hanzi import characters
import re 

text = '生活就像【】,如果##'

temp = re.sub('[{}]'.format(characters),'',text)
print(temp)

'''
'【】,##'
'''

去除英文

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

'''
'  # ! 223'
'''

去除数字

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

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

'''
'哈aksjn ekljfk # ! len'
'''

去除空格

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

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

'''
'aksjn ekljfk # ! len223'
'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值