Python实现简单文本字符串处理的方法

巷口听风
巷口听风
发布时间:2026-10-13| 3人浏览过
原创

本文介绍Python中处理文本字符串的常用技巧。通过string.split()进行基础分割,利用正则表达式排除标点符号,过滤空字符串,并使用.lower()统一大小写。结合完整邮件示例,展示从原始文本到标准化词表的完整处理流程,适用于基础NLP数据清洗场景。

本文介绍了利用Python进行基础文本字符串处理的具体实现方式,供读者参考学习。

针对文本字符串,可以使用Python的string.split()方法执行切割操作。以下展示具体的运行效果。

mySent = 'This book is the best book on python!'
print mySent.split()

输出结果如下:

['This', 'book', 'is', 'the', 'best', 'book', 'on', 'python!']

从结果可见,分割效果良好,但标点符号也被识别为独立词汇。为解决此问题,可引入正则表达式进行处理,设定分隔符为除单词和数字外的任意字符序列。

import re
reg = re.compile('\\W*')
mySent = 'This book is the best book on python!'
listof = reg.split(mySent)
print listof

处理后的输出结果为:

['This', 'book', 'is', 'the', 'best', 'book', 'on', 'python', '']

此时获得了一个由词汇组成的列表,但其中包含空字符串,需要将其剔除。

可通过计算每个字符串的长度,仅保留长度大于0的字符串元素。

import re
reg = re.compile('\\W*')
mySent = 'This book is the best book on python!'
listof = reg.split(mySent)
new_list = [tok for tok in listof if len(tok)>0]
print new_list

最终输出结果为:

['This', 'book', 'is', 'the', 'best', 'book', 'on', 'python']

此外,注意到句子首字母存在大写情况。为实现格式统一,需将大写转换为小写。Python内置方法提供了将字符串全部转为小写(.lower())或大写(.upper())的功能。

import re
reg = re.compile('\\W*')
mySent = 'This book is the best book on python!'
listof = reg.split(mySent)
new_list = [tok.lower() for tok in listof if len(tok)>0]
print new_list

转换后的输出结果为:

['this', 'book', 'is', 'the', 'best', 'book', 'on', 'python']

接下来分析一封完整的电子邮件内容:

邮件正文内容

Hi Peter,

With Jose out of town, do you want to
meet once in a while to keep things
going and do some interesting stuff?

Let me know
Eugene

import re
reg = re.compile('\\W*')
email = open('email.txt').read()
list = reg.split(email)
new_txt = [tok.lower() for tok in list if len(tok)>0]
print new_txt

处理输出结果:

复制代码 代码如下:
['hi', 'peter', 'with', 'jose', 'out', 'of', 'town', 'do', 'you', 'want', 'to', 'meet', 'once', 'in', 'a', 'while', 'to', 'keep', 'things', 'going', 'and', 'do', 'some', 'interesting', 'stuff', 'let', 'me', 'know', 'eugene']

如需了解更多Python相关知识,可查阅本站专题:《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》。

希望本文所述内容能对您的Python程序设计有所帮助。

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

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 算法库。