给定一个包含gzipped文件的文件夹,我想创建一个语料库:
以下操作失败
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正确的方法是什么?
我使用python3.6和nltk 3.2.2
发布于 2017-05-03 20:58:16
nltk的阅读器可以处理存储为压缩的文件存档的语料库。您有一个包含gzipped文件的常规目录,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")https://stackoverflow.com/questions/43721142
复制相似问题