NLTK 单词与 word_tokenize

Cas*_*rey 4 python nlp corpus tokenize nltk

我正在探索 NLTK 的一些语料库并遇到以下行为:word_tokenize() 和 words 产生不同的 words() 集

下面是一个使用 webtext 的例子:

from nltk.corpus import webtext
Run Code Online (Sandbox Code Playgroud)

当我运行以下命令时,

len(set(word_tokenize(webtext.raw('wine.txt'))))
Run Code Online (Sandbox Code Playgroud)

我得到:3488

当我运行以下命令时,

len(set(webtext.words('wine.txt')))
Run Code Online (Sandbox Code Playgroud)

我得到:3414

我在文档中只能找到 word_tokenize 是标点符号和单词的列表。但它也说单词是标点符号和单词的列表。我想知道,这里发生了什么?他们为什么不同?

我已经尝试查看设置差异。

U = set(word_tokenize(webtext.raw('wine.txt')))
V = set(webtext.words('wine.txt'))

tok_not_in_words = U.difference(V) # in tokenize but not in words
words_not_in_tok = V.difference(U) # in words but not in tokenize
Run Code Online (Sandbox Code Playgroud)

我只能看到 word_tokenize 包含带连字符的单词,而单词将带连字符的单词分开。

任何帮助表示赞赏。谢谢!

alv*_*vas 5

首先让我们看一下两种方法中标记的计数并查看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
Run Code Online (Sandbox Code Playgroud)

有什么鱼腥味...

让我们如何仔细看看webtext接口能够实现,它采用了LazyCorpusLoaderhttps://github.com/nltk/nltk/blob/develop/nltk/corpus/初始化的.py#L235

webtext = LazyCorpusLoader(
    'webtext', PlaintextCorpusReader, r'(?!README|\.).*\.txt', encoding='ISO-8859-2')
Run Code Online (Sandbox Code Playgroud)

如果我们看看如何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'):
Run Code Online (Sandbox Code Playgroud)

啊哈!它正在使用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/初始化的.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)])
Run Code Online (Sandbox Code Playgroud)

以达到_read_word_block()https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L119

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
Run Code Online (Sandbox Code Playgroud)

它正在逐行读取文件!

所以如果我们加载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
Run Code Online (Sandbox Code Playgroud)

更多奥秘

您还可以webtext通过指定 tokenizer 对象来创建一个新的语料库对象,例如

>>> 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']
Run Code Online (Sandbox Code Playgroud)

这是因为word_tokenize一个做sent_tokenize其实之前令牌化的句子进言:https://github.com/nltk/nltk/blob/develop/nltk/tokenize/初始化的.py#L113

但是事先PlaintextCorpusReader. _read_word_block()没有做sent_tokenizehttps://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
Run Code Online (Sandbox Code Playgroud)

注意:sent_tokenizerofPlaintextCorpusReader使用sent_tokenizer=nltk.data.LazyLoader('tokenizers/punkt/english.pickle')nltk.sent_tokenize()函数共享的同一个对象。

瞧!

为什么words()不先做句子标记化?

我认为这是因为它最初使用的WordPunctTokenizer是不需要先对字符串进行句子标记化,而TreebankWordTokenizer需要先对字符串进行标记化。

为什么在“深度学习”和“机器学习”时代,我们还在使用基于正则表达式的分词器,而 NLP 中的其他一切都主要基于这些分词?

我没有想法......但有替代方案,例如http://gmb.let.rug.nl/elephant/about.php