Python3 中高效去除字符串标点符号的方法

Aria
Aria
发布时间:2026-10-13| 6人浏览过
原创

本文介绍在Python3环境下去除字符串标点符号的有效方法。通过对比Python2的旧式实现,重点讲解了利用string.maketrans和str.translate构建翻译表来批量移除标点符号的技巧,并提供完整代码示例及参考链接,帮助开发者快速实现字符串清洗。

网络上关于Python去除字符串标点符号的教程多基于Python2版本,在Python3中往往无法直接适用。经过调整适配后,具体的实现代码如下所示:

代码

lower_case_documents = ['Hello, how are you!','Win money, win from home.','Call me now.','Hello, Call hello you tomorrow?']
sans_punctuation_documents = []
import string

for i in lower_case_documents:
  # TODO
  trantab = str.maketrans({key: None for key in string.punctuation})
  j = i.translate(trantab)
  sans_punctuation_documents.append(j)

print(sans_punctuation_documents)

['hello how are you', 'win money win from home', 'call me now', 'hello call hello you tomorrow']

参考

https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python

以上就是Python3去除字符串中标点符号方法的详细介绍,希望能为各位读者提供实用的参考,同时也欢迎大家继续支持本站获取更多技术内容。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。