Python 如何从字符串中去除所有标点符号

Python 如何从字符串中去除所有标点符号

可以使用多种方法从Python字符串中去除所有标点符号。以下是一些示例:

使用string.punctuation

示例

string.punctuation常量包含所有ASCII标点符号字符。我们可以使用这个常量来从字符串中去除所有标点符号。

我们使用列表推导式遍历字符串中的每个字符,并检查它是否不在string.punctuation常量中。如果它不是标点字符,我们将它添加到no_punct变量中。

import string
# sample string with punctuation
text = "Lorem, Ipsum!!!"
# remove punctuation
no_punct = "".join(char for char in text if char not in string.punctuation)
print(no_punct)

输出

Lorem Ipsum

使用正则表达式

我们也可以使用正则表达式从字符串中删除所有标点符号。

示例

我们使用re.sub()方法将所有非单词字符和非空格字符替换为空字符串。

import re

# sample string with punctuation
text = "Lorem, Dolor!!!"

# remove punctuation using regular expression
no_punct = re.sub(r'[^\w\s]', '', text)

print(no_punct)

输出

Lorem Dolor

使用translate()

translate()方法也可以用来从字符串中删除标点符号。

示例

我们正在使用str.maketrans()方法创建一个翻译表,并将其传递给translate()方法,以从字符串中删除表中的所有字符。

import string
# sample string with punctuation
text = "Lorem, Ipsum!!!"
# create a translation table
table = str.maketrans('', '', string.punctuation)
# remove punctuation
no_punct = text.translate(table)
print(no_punct)

输出

Lorem Ipsum

以下是如何在Python中从字符串中去除所有标点符号的更多示例:

使用循环遍历字符

我们也可以遍历字符串中的每个字符,并删除任何标点符号字符。

示例:

我们正在遍历字符串中的每个字符,并检查它是否是字母或数字,或者是空格字符。如果是,我们将其添加到no_punct变量中。这样,我们就从结果字符串中排除了任何标点符号字符。

# sample string with punctuation
text = "Foo, Bar!!!"
# remove punctuation using a loop
no_punct = ""
for char in text:
    if char.isalnum() or char.isspace():
        no_punct += char
print(no_punct)

输出

Foo Bar

使用replace()方法

我们还可以使用replace()方法从字符串中删除所有标点符号。

示例

我们正在使用replace()方法将每个标点符号(句号、逗号、感叹号和问号)替换为空字符串。这样,我们就从字符串中删除了所有标点符号。

# sample string with punctuation
text = "Fubar, Quz!!!"
# remove punctuation using the replace() method
no_punct = text.replace(".", "").replace(",", "").replace("!", "").replace("?", "")
print(no_punct)

输出

Fubar Quz

在使用标点符号字符列表时使用re模块

我们还可以使用re模块,通过一个标点符号字符列表来从字符串中删除所有标点符号字符。

示例

我们使用re.sub()方法,将所有非字母、数字或空格的字符替换为空字符串。正则表达式[^a−zA−Z0−9\s]+匹配任何不是字母、数字或空格字符的字符。

import re
# sample string with punctuation
text = "Foobar, Baz?"
# remove punctuation using the re module and a list of punctuation characters
no_punct = re.sub('[^a-zA-Z0-9\s]+', '', text)
print(no_punct)

输出

Foobar Baz

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程