迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

如何在 Python 中从一个字符串中删除标点符号

作者:迹忆客 最近更新:2023/12/17 浏览次数:

本教程讨论了在 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'

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便