这些对象均来自nltk.tokenize库
1. word_tokenize
导入nltk的tokenize库后,tokens = nltk.word_tokenize(sentence)语句进行分词操作,sentence为待处理的字符串。返回一个列表。
该方法要求被处理的字符串本身各个词语之间有空格,能处理如don't, they'll等缩写词的情况。
2. TweetTokenizer
Twitter-aware,按空格进行分词,同时针对推文一些特性,去除@用户名,保留表情等一些特殊符号。
分两种:
(1)不带参数token=TweetTokenizer().tokenize(sentence)处理。
输入"This is a coooool #dummysmiley: :-) :-P <3 and some arrows < > -> <--"
输出['This', 'is', 'a', 'cooool', '#dummysmiley', ':', ':-)', ':-P', '<3', 'and', 'some', 'arrows', '<', '>', '->', '<--']能够拆分无效用的标点符号。
(2)带参数token = TweetTokenizer(strip_handles=True, reduce_len = True).
输入@remy: This is waaaaayyyy too much for you!!!!!!
输出[':', 'This', 'is', 'waaayyy', 'too', 'much', 'for', 'you', '!', '!', '!']
当一个词中相同字符连续出现3次以上,就只保留3个。设置strip_handles = True会删去@xxx。
3. MWETokenizer
tokenizer = MWETokenizer([('a', 'little'), ('a', 'little', 'bit'), ('a', 'lot')])
输入tokenizer.tokenize('In a litte or a litte bit or a lot in spite of'.split()); tokenizer.add_mwe(('in', 'spite', 'of'))
输出['In', 'a_little', 'or', 'a_little_bit', 'or', 'a_lot', 'in_spite_of']
该方法可对已经先保留的一些短语,或者组合,进行重组(对一些专有词可以先进行保留,如F-16,最后重组已保留-)。
4. RegexpTokenizer
使用到正则表达式进行分词,如对一些金钱表示或者其他非空白序列。
tokenizer = RegexpTokenizer('\w+|\$[\d\.]+|\S+')
输入"Good muffins cost $3.88\n in New York. Please buy me\n two of them.\n\n Thanks."
输出['Good', 'muffins', 'cost', '$3.88', 'in', 'New', 'York', '.', 'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
5. StanfordTokenizer
按空格进行分词,对于$4.28之类的,将符号与数字分开。
输入“Good muffins cost $3.88\n in New York. Please buy me\n two of them.\n Thanks."
输出['Good', 'muffins', 'cost', '$', '3.88', 'in', 'New', 'York', '.', 'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']