nltk - gzip压缩文件的语料库

时间:2017-05-01 14:53:32

标签: python nltk

给定一个带有gzip压缩文件的文件夹,我想创建一个语料库:

以下失败

from nltk.corpus import PlaintextCorpusReader
wordlists = PlaintextCorpusReader('.', '.*')
wordlists.words('a.txt.gz')

错误消息是:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/anaconda3/lib/python3.6/site-packages/nltk/collections.py", line 225, in __repr__
    for elt in self:
  File "/anaconda3/lib/python3.6/site-packages/nltk/corpus/reader/util.py", line 296, in iterate_from
    tokens = self.read_block(self._stream)
  File "/anaconda3/lib/python3.6/site-packages/nltk/corpus/reader/plaintext.py", line 122, in _read_word_block
    words.extend(self._word_tokenizer.tokenize(stream.readline()))
  File "/anaconda3/lib/python3.6/site-packages/nltk/data.py", line 1142, in readline
    new_chars = self._read(readsize)
  File "/anaconda3/lib/python3.6/site-packages/nltk/data.py", line 1374, in _read
    chars, bytes_decoded = self._incr_decode(bytes)
  File "/anaconda3/lib/python3.6/site-packages/nltk/data.py", line 1405, in _incr_decode
    return self.decode(bytes, 'strict')
  File "/anaconda3/lib/python3.6/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

这样做的正确方法是什么?

我正在使用python 3.6和nltk 3.2.2

1 个答案:

答案 0 :(得分:1)

nltk的读者可以处理存储为压缩档案档案的语料库。你有一个充满gzip压缩文件的常规目录,nltk似乎没有开箱即用的文件;无论如何,一个大型存档通常比几个小存档更紧凑,因此您可以通过切换到单个压缩存档来解决您的问题。

我能够让nltk读取一个压缩(非gzipped)的存档,如下所示:

    % unzip -l big-corpus.zip
    Archive:  big-corpus.zip
      Length     Date   Time    Name
     --------    ----   ----    ----
            0  05-08-14 00:34   big-corpus/
         5258  05-08-14 00:34   big-corpus/austen-emma.txt
         5391  05-08-14 00:34   big-corpus/austen-persuasion.txt
         ...

即,语料库文件应该在子目录中。出于某种原因,我无法让读者接受包含顶层文件的存档(没有子目录)。获得此结构的一种方法是,如果您有一个包含语料库的文件夹big-corpus,并在包含big-corpus的目录中执行以下命令:

% zip -r big-corpus.zip big-corpus

完成此操作后,只需使用以下语法初始化阅读器:

corpus = PlaintextCorpusReader("big-corpus.zip/big-corpus/", r".*\.txt")