Python中文本分割的具体方式

在机器学习实战一书朴素贝叶斯部分提及文本切分,切分文本的常用方法是使用split()函数,无法分开形如 M.L.的字符串,
实例如下:
mySent='This book is the best book on Python or M.L. I have ever laid eyes upon.'

mySent.split()
Out[23]: 
['This','book','is','the','best','book','on','Python','or','M.L.','I','have','ever','laid','eyes','upon.']

很明显,可以看到'M.L.'和'upon.'与我们所期望提取到的字符串有较大偏差
这里推荐使用re 模块中的正则表示式来切分句子,其中的分隔符是除单词,数字外的任意字符串.
import re
regEx=re.compile(r'\W*')
lists=regEx.split(mySent)
__main__:1: FutureWarning: split() requires a non-empty pattern match.

lists
Out[28]: 
['This',
 'book',
 'is',
 'the',
 'best',
 'book',
 'on',
 'Python',
 'or',
 'M',
 'L',
 'I',
 'have',
 'ever',
 'laid',
 'eyes',
 'upon',
 '']

再外加判断字符串长度来除去'  '空字符

[tok.lower() for tok in lists if len(tok)>0]
Out[29]: 
['this',
 'book',
 'is',
 'the',
 'best',
 'book',
 'on',
 'python',
 'or',
 'm',
 'l',
 'i',
 'have',
 'ever',
 'laid',
 'eyes',
 'upon']

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值