gpt4 book ai didi

python - 如何确定语料库中的哪些文本包含Python中的NLTK套件生成的错误?

转载 作者:行者123 更新时间:2023-12-03 08:43:05 24 4
gpt4 key购买 nike

我正在尝试使用Python进行一些基本的语料库分析。我收到以下错误消息:

Traceback (most recent call last):
File "<pyshell#28>", line 2, in <module>
print(len(poems.words(f)), f)
File "C:\Python38-32\lib\site-packages\nltk\corpus\reader\util.py", line 240, in __len__
for tok in self.iterate_from(self._toknum[-1]):
File "C:\Python38-32\lib\site-packages\nltk\corpus\reader\util.py", line 306, in iterate_from
tokens = self.read_block(self._stream)
File "C:\Python38-32\lib\site-packages\nltk\corpus\reader\plaintext.py", line 134, in _read_word_block
words.extend(self._word_tokenizer.tokenize(stream.readline()))
File "C:\Python38-32\lib\site-packages\nltk\data.py", line 1220, in readline
new_chars = self._read(readsize)
File "C:\Python38-32\lib\site-packages\nltk\data.py", line 1458, in _read
chars, bytes_decoded = self._incr_decode(bytes)
File "C:\Python38-32\lib\site-packages\nltk\data.py", line 1489, in _incr_decode
return self.decode(bytes, 'strict')
File "C:\Python38-32\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x97 in position 12: invalid start byte

我的假设是,我正在查看的202个文本文件之一存在UTF错误。
从错误消息中,有什么方法可以告诉哪个文件有问题?

最佳答案

假设您知道文件ID(语料库文件的路径),则可以使用encoding="utf-8"打开所有文件

如果您不知道路径,那么假设您正在使用nltk语料库加载器,则可以使用以下命令获取它们:

poems.fileids()

之后,对于文件列表中的每个文件(例如 fileids),您都可以尝试:
for file_ in fileids:
try:
with open(file_, encoding="utf-8") a f_i:
f_i.readlines()
except:
print("You got problems with the file: ", file_)

无论如何,您的加载程序还具有一个名为“encoding”的参数,您可以使用该参数对语料库进行正确的编码。默认情况下设置为“utf-8”

此处有更多详细信息: nltk corpus loader

关于python - 如何确定语料库中的哪些文本包含Python中的NLTK套件生成的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59912210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com