切分文本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对象不是列表对象