📌  相关文章
📜  删除字符串标点符号 python 3 - Python (1)

📅  最后修改于: 2023-12-03 14:50:19.030000             🧑  作者: Mango

Python 3 - 删除字符串标点符号

在文本处理中,我们有时需要将字符串中的标点符号删除,以便更好地进行分词、计算等操作。本篇介绍如何使用 Python 3 进行字符串标点符号的删除。

方法一:使用 re.sub()

我们可以使用 re.sub() 函数,结合正则表达式,将字符串中的标点符号替换为空字符串,从而达到删除的效果。

import re

def remove_punctuation(text):
    cleaned = re.sub(r'[^\w\s]', '', text)
    return cleaned

text = "Hello! How are you?"
print(remove_punctuation(text)) # Output: Hello How are you

在上述代码中,我们使用了正则表达式 r'[^\w\s]' 来匹配非字母数字和空白字符,即标点符号。re.sub() 函数将匹配到的字符替换为空字符串,返回清除标点符号后的字符串。

方法二:使用 string.punctuation

Python 3 中一个有用的字符串常量是 string.punctuation,其中包含了所有标点符号。我们可以将待删除的字符与 string.punctuation 做比较,将不是标点符号的字符放入到列表中,最终将列表转换为字符串。

import string

def remove_punctuation(text):
    cleaned = "".join([c for c in text if c not in string.punctuation])
    return cleaned

text = "Hello! How are you?"
print(remove_punctuation(text)) # Output: Hello How are you

在上述代码中,我们使用了列表推导式,循环遍历字符串中的每一个字符 c,判断 c 是否是标点符号,如果不是则将 c 放入到新的列表中。最后使用 join() 函数将列表中的字符连接起来,最终得到清除标点符号后的字符串。

总的来说,两种方法都可以有效删除字符串中的标点符号,具体选择哪种方法可以根据实际需求和性能进行选择。