Python实现简单文本字符串处理的方法
本文介绍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程序设计有所帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













