切分文本Python

 这篇文章也是好久之前的了,当初学机器学习有个要处理文件的操作,就总结了一下,当初存的日记,现在看到是Python的小技巧,分享给大家🙂。不当之处还请大佬指导(当初还是小白,不会使用插入代码,代码都是手打的🤦‍)

1.我们可以使用Python中的string.split()的方法将其切分

>>>mySent = 'This!!! book is the best book on Python or M.L I have ever laid eyes upon'

>>>mySent.split()

>>>['This!!!','book','is','the','best','book','on','Python','or','M.L.','I','have','ever','laid','eyes','upon.']

可以看到标点符号也被当成词的一部分

2.我们可以用正则来切分句子,其中分隔符是除单词、数字外的任意字符串。

>>> import re

>>> regEx = re.compile('\\W')                                       

>>>listOfTokens = regEx.split(mySent)

>>>listOfTokens

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

上述结果我们发现存在空字符串  ‘’ 我们使用列表推导式

>>>[tok for tok in listOfTokens if len(tok)>0]

又因为存在大写字母,因为在词袋中无论位置在哪里都应该是小写因此可以使用python中的(.lower())或者大写(.upper())

>>>[tok.lower() for tok in listOfTokens if len(tok)>0]

['this','book','is','the','best','book','on','python','or','m','l','i','have','ever','laid','eyes','upon']

3.python3.x中range返回的是range对象不是列表对象