Skip to main content
 首页 » 编程设计

python之nltk之gzip 文件语料库

2025年02月15日8tuyile006

给定一个包含压缩文件的文件夹,我想创建一个语料库:

以下失败

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

请您参考如下方法:

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