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

yipeiwu_com5年前Python基础

本文实例讲述了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面向对象类编写细节分析【类,方法,继承,超类,接口等】

本文实例讲述了Python面向对象类编写技术细节。分享给大家供大家参考,具体如下: 类代码编写细节 继续学习类、方法和继承。 class语句 以下是class语句的一般形式: cla...

python实现在函数中修改变量值的方法

和其他语言不一样,传递参数的时候,python不允许程序员选择采用传值还是传引用。Python参数传递采用的肯定是“传对象引用”的方式。 实际上,这种方式相当于传值和传引用的一种综合。如...

和孩子一起学习python之变量命名规则

变量命名规则 下面是关于变量名(也称为标识符)的一些规则 必须以一个字母或一个下划线字符开头。后面可以使用一个字母、数字或下划线字符的序列,长度不限。 字母可以是大写或小写,大小写...

Python简单实现控制电脑的方法

本文实例讲述了Python简单实现控制电脑的方法。分享给大家供大家参考,具体如下: 1、windows 下,CMD的一些命令: dir:列出当前的所有文件 time:打印当前的时间 tr...

Python正则表达式教程之二:捕获篇

前言 在上一篇文中,我们介绍了关于Python正则表达式的基础,那么在这一篇文章里,我们将总结一下正则表达式关于捕获的用法。下面话不多说,来看看详细的介绍吧。  &n...