如何在 Python 中从一个字符串中删除标点符号
本教程讨论了在 Python 中从字符串中删除标点符号的方法。这是 NLP 预处理和清理文本数据时特别有用的一步。
在 Python 中使用 string
类方法从字符串中删除标点符号
我们可以使用 String
类提供的内置函数,在 Python 中从字符串中删除标点符号。下面的例子说明了这一点。
s = "string. With. Punctuations!?"
out = s.translate(str.maketrans("", "", string.punctuation))
print(out)
输出:
'string With Punctuations'
上面的方法从一个给定的输入字符串中删除了所有的标点符号。
在 Python 中使用 regex
从字符串中删除标点符号
我们也可以在 Python 中使用 regex
从字符串中删除标点符号。下面的例子说明了这一点。
import re
s = "string. With. Punctuation?"
out = re.sub(r"[^\w\s]", "", s)
print(out)
输出:
'string With Punctuations'
在 Python 中使用 string.punctuation
从一个字符串中删除标点符号
它与讨论的第一种方法类似。string.punctuation
包含了所有在英语中被认为是标点符号的字符。我们可以使用这个列表,从一个字符串中排除所有的标点符号。下面的例子说明了这一点。
s = "string. With. Punctuation?"
out = "".join([i for i in s if i not in string.punctuation])
print(out)
输出:
'string With Punctuations'
在 Python 中使用 replace()
从字符串中删除标点符号
在 Python 中,我们还可以使用 replace()
从一个字符串中删除出标点符号。同样,我们使用 string.punctuation
来定义一个标点符号的列表,然后用一个空字符串替换所有的标点符号来删除标点符号。下面的例子说明了这一点。
s = "string. With. Punctuation?"
punct = string.punctuation
for c in punct:
s = s.replace(c, "")
print(s)
输出:
'string With Punctuations'
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串