2017-05-01 151 views
2

考虑到与gzip压缩文件的文件夹我想创建一个语料库语料库: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

+0

是解压缩文件的一个选项?这会让生活变得更容易。 – alexis

+0

不可以。我想让它们以gzip格式保存空间。 –

回答

1

的NLTK的读者可以处理存储为文件的压缩文档的语料库。你有一个普通的目录,里面装满了gzip文件,nltk看起来并不适合开箱即用;无论如何,一个大档案通常比几个小档案更紧凑,所以你可以通过切换到单个压缩档案来解决你的问题。

我能得到的NLTK读取压缩(不gzip压缩)压缩文件,看起来像这样:

% 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")