如何在 Python 中从一个字符串中删除标点符号 您所在的位置:网站首页 遂川汽车站官网首页网址查询 如何在 Python 中从一个字符串中删除标点符号

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

2024-06-14 16:22| 来源: 网络整理| 查看: 265

在 Python 中使用 string 类方法从字符串中删除标点符号 在 Python 中使用 regex 从字符串中删除标点符号 在 Python 中使用 string.punctuation 从一个字符串中删除标点符号 在 Python 中使用 replace() 从字符串中删除标点符号

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


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有