在Python中删除标点符号,你可以使用以下几种方法:
1. 使用`str.isalnum()`方法:
import string
text = "Special $! characters spaces "
result = ''.join(e for e in text if e.isalnum())
print(result) 输出:Specialcharactersspaces
2. 使用`str.translate()`和`str.maketrans()`方法:
import string
text = "Hello, World! This is a test string."
translator = str.maketrans('', '', string.punctuation)
result = text.translate(translator)
print(result) 输出:Hello World This is a test string
3. 使用正则表达式(`re`模块):
import re
text = "测试。。去除标点。。"
result = re.sub(r'[^\w\s]', '', text)
print(result) 输出:测试去除标点
4. 使用`zhon`包处理中文标点符号:
from zhon.hanzi import punctuation
import re
text = "测试。。去除标点。。"
result = re.sub(format(punctuation), '', text.decode('utf-8'))
print(result) 输出:测试去除标点