首页 技术 正文
技术 2022年11月14日
0 收藏 508 点赞 4,954 浏览 1411 个字

对于一个文本字符串,可以使用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模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,914
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,438
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,252
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,063
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,698
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,734