首先让我们看一下这两种方法的令牌计数,并查看most_common 字词:
>>> import nltk
>>> from nltk import word_tokenize
>>> from nltk.corpus import webtext
>>> counts_from_wordtok = Counter(word_tokenize(webtext.raw('wine.txt')))
>>> counts_from_wordtok.most_common(10)
[(u'.', 2824), (u',', 1550), (u'a', 821), (u'and', 786), (u'the', 706), (u'***', 608), (u'-', 518), (u'of', 482), (u'but', 474), (u'I', 390)]
>>> counts_from_words = Counter(webtext.words('wine.txt'))
>>> counts_from_words.most_common(10)
[(u'.', 2772), (u',', 1536), (u'-', 832), (u'a', 821), (u'and', 787), (u'the', 706), (u'***', 498), (u'of', 482), (u'but', 474), (u'I', 392)]
>>> len(word_tokenize(webtext.raw('wine.txt')))
31140
>>> len(webtext.words('wine.txt'))
31350
有些东西闻起来很腥......
让我们仔细看看webtext 接口是如何产生的,它使用LazyCorpusLoader https://github.com/nltk/nltk/blob/develop/nltk/corpus/init.py#L235
webtext = LazyCorpusLoader(
'webtext', PlaintextCorpusReader, r'(?!README|\.).*\.txt', encoding='ISO-8859-2')
如果我们看看PlaintextCorpusReader 是如何加载语料库并标记https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L41
class PlaintextCorpusReader(CorpusReader):
CorpusView = StreamBackedCorpusView
def __init__(self, root, fileids,
word_tokenizer=WordPunctTokenizer(),
sent_tokenizer=nltk.data.LazyLoader(
'tokenizers/punkt/english.pickle'),
para_block_reader=read_blankline_block,
encoding='utf8'):
啊哈!它使用WordPunctTokenizer 而不是默认修改的TreebankTokenizer
WordPunctTokenizer 是一个简单的标记器,位于 https://github.com/nltk/nltk/blob/develop/nltk/tokenize/regexp.py#L171
word_tokenize() 函数是经过修改的 TreebankTokenizer,它是 NLTK 独有的 https://github.com/nltk/nltk/blob/develop/nltk/tokenize/init.py#L97
如果我们查看webtext.words() 调用的内容,我们会关注https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L81
def words(self, fileids=None):
"""
:return: the given file(s) as a list of words
and punctuation symbols.
:rtype: list(str)
"""
return concat([self.CorpusView(path, self._read_word_block, encoding=enc)
for (path, enc, fileid)
in self.abspaths(fileids, True, True)])
通过https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L119 联系_read_word_block():
def _read_word_block(self, stream):
words = []
for i in range(20): # Read 20 lines at a time.
words.extend(self._word_tokenizer.tokenize(stream.readline()))
return words
它正在逐行读取文件!
因此,如果我们加载 webtext 语料库并使用 WordPunctTokenizer,我们会得到相同的数字:
>>> from nltk.corpus import webtext
>>> from nltk.tokenize import WordPunctTokenizer
>>> wpt = WordPunctTokenizer()
>>> len(wpt.tokenize(webtext.raw('wine.txt')))
31350
>>> len(webtext.words('wine.txt'))
31350
更多谜团
您还可以通过指定标记器对象来创建新的webtext 语料库对象,例如
>>> from nltk.tokenize import _treebank_word_tokenizer
>>> from nltk.corpus import LazyCorpusLoader, PlaintextCorpusReader
>>> from nltk.corpus import webtext
# LazyCorpusLoader expects a tokenizer object,
# but word_tokenize() is a function, so we have to
# import the tokenizer object that word_tokenize wraps around
>>> webtext2 = LazyCorpusLoader('webtext', PlaintextCorpusReader, r'(?!README|\.).*\.txt', encoding='ISO-8859-2', word_tokenizer=_treebank_word_tokenizer)
>>> len(webtext2.words('wine.txt'))
28385
>>> len(word_tokenize(webtext2.raw('wine.txt')))
31140
>>> list(webtext2.words('wine.txt'))[:100]
[u'Lovely', u'delicate', u',', u'fragrant', u'Rhone', u'wine.', u'Polished', u'leather', u'and', u'strawberries.', u'Perhaps', u'a', u'bit', u'dilute', u',', u'but', u'good', u'for', u'drinking', u'now.', u'***', u'Liquorice', u',', u'cherry', u'fruit.', u'Simple', u'and', u'coarse', u'at', u'the', u'finish.', u'**', u'Thin', u'and', u'completely', u'uninspiring.', u'*', u'Rough.', u'No', u'Stars', u'Big', u',', u'fat', u',', u'textured', u'Chardonnay', u'-', u'nuts', u'and', u'butterscotch.', u'A', u'slightly', u'odd', u'metallic/cardboard', u'finish', u',', u'but', u'probably', u'***', u'A', u'blind', u'tasting', u',', u'other', u'than', u'the', u'fizz', u',', u'which', u'included', u'five', u'vintages', u'of', u'Cote', u'Rotie', u'Brune', u'et', u'Blonde', u'from', u'Guigal', u'.', u'Surprisingly', u'young', u'feeling', u'and', u'drinking', u'well', u',', u'but', u'without', u'any', u'great', u'complexity.', u'A', u'good', u'***', u'Charming', u',', u'violet-fragranced', u'nose.']
>>> word_tokenize(webtext2.raw('wine.txt'))[:100]
[u'Lovely', u'delicate', u',', u'fragrant', u'Rhone', u'wine', u'.', u'Polished', u'leather', u'and', u'strawberries', u'.', u'Perhaps', u'a', u'bit', u'dilute', u',', u'but', u'good', u'for', u'drinking', u'now', u'.', u'***', u'Liquorice', u',', u'cherry', u'fruit', u'.', u'Simple', u'and', u'coarse', u'at', u'the', u'finish', u'.', u'**', u'Thin', u'and', u'completely', u'uninspiring', u'.', u'*', u'Rough', u'.', u'No', u'Stars', u'Big', u',', u'fat', u',', u'textured', u'Chardonnay', u'-', u'nuts', u'and', u'butterscotch', u'.', u'A', u'slightly', u'odd', u'metallic/cardboard', u'finish', u',', u'but', u'probably', u'***', u'A', u'blind', u'tasting', u',', u'other', u'than', u'the', u'fizz', u',', u'which', u'included', u'five', u'vintages', u'of', u'Cote', u'Rotie', u'Brune', u'et', u'Blonde', u'from', u'Guigal', u'.', u'Surprisingly', u'young', u'feeling', u'and', u'drinking', u'well', u',', u'but', u'without', u'any', u'great']
这是因为word_tokenize 在将句子实际标记为单词之前执行了sent_tokenize:https://github.com/nltk/nltk/blob/develop/nltk/tokenize/init.py#L113
但是PlaintextCorpusReader. _read_word_block() 事先没有sent_tokenize,https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L119
让我们先用句子标记化来重新计算一下:
>>> len(word_tokenize(webtext2.raw('wine.txt')))
31140
>>> sum(len(tokenized_sent) for tokenized_sent in webtext2.sents('wine.txt'))
31140
注意:PlaintextCorpusReader 的 sent_tokenizer 使用 sent_tokenizer=nltk.data.LazyLoader('tokenizers/punkt/english.pickle'),这是与 nltk.sent_tokenize() 函数共享的同一对象。
瞧!
为什么words()不先做句子分词?
我认为是因为它最初使用 WordPunctTokenizer 不需要首先对字符串进行标记化,而 TreebankWordTokenizer 需要首先对字符串进行标记化。
为什么在“深度学习”和“机器学习”时代,我们仍在使用基于正则表达式的分词器,而 NLP 中的其他一切都主要基于这些词?
我不知道...但是有其他选择,例如http://gmb.let.rug.nl/elephant/about.php