在语料库中查找损坏的文件 Python
Finding the broken file in a corpus Python
我正在使用 Python 的 NLTK TaggedCorpusReader 创建文本文件语料库。但是,其中一个文件不是 utf-8 格式或具有不受支持的字符。有什么方法可以判断哪个文件包含问题?
这是我的代码:
import nltk
corpus=nltk.corpus.TaggedCorpusReader("filepath", '.*.txt', encoding='utf-8') #I added the encoding when I saw some answer about that, but it doesn't seem to help
words=corpus.words()
for w in words:
print(w)
我的错误:
UnicodeDecodeError:'utf-8' 编解码器无法解码位置 0 中的字节 0xa0:起始字节无效
您可以通过一次读取一个文件来识别文件,如下所示:
corpus = nltk.corpus.TaggedCorpusReader("filepath", r'.*\.txt', encoding='utf-8')
try:
for filename in corpus.fileids():
words_ = corpus.words(filename)
except UnicodeDecodeError:
print("UnicodeDecodeError in", filename)
(或者您可以在阅读之前打印每个文件名,甚至不必费心捕获错误。)
找到文件后,您必须找出问题的根源。你的语料库真的是 utf-8 编码的吗?也许它正在使用另一种 8 位编码,例如 Latin-1 或其他。指定一个 8 位编码不会给你一个错误(在这些格式中没有错误检查),但你可以要求 python 打印一些行并查看所选编码是否正确。
如果你的语料库几乎完全是英文的,你可以在文件中搜索包含非 ascii 字符的行并只打印这些:
testreader = nltk.corpus.TaggedCorpusReader("filepath", r".*\.txt", encoding="Latin-1")
for line in testreader.raw(badfilename).splitlines():
if re.search(r'[\x80-\xFF]', line)):
print(line)
我正在使用 Python 的 NLTK TaggedCorpusReader 创建文本文件语料库。但是,其中一个文件不是 utf-8 格式或具有不受支持的字符。有什么方法可以判断哪个文件包含问题?
这是我的代码:
import nltk
corpus=nltk.corpus.TaggedCorpusReader("filepath", '.*.txt', encoding='utf-8') #I added the encoding when I saw some answer about that, but it doesn't seem to help
words=corpus.words()
for w in words:
print(w)
我的错误:
UnicodeDecodeError:'utf-8' 编解码器无法解码位置 0 中的字节 0xa0:起始字节无效
您可以通过一次读取一个文件来识别文件,如下所示:
corpus = nltk.corpus.TaggedCorpusReader("filepath", r'.*\.txt', encoding='utf-8')
try:
for filename in corpus.fileids():
words_ = corpus.words(filename)
except UnicodeDecodeError:
print("UnicodeDecodeError in", filename)
(或者您可以在阅读之前打印每个文件名,甚至不必费心捕获错误。)
找到文件后,您必须找出问题的根源。你的语料库真的是 utf-8 编码的吗?也许它正在使用另一种 8 位编码,例如 Latin-1 或其他。指定一个 8 位编码不会给你一个错误(在这些格式中没有错误检查),但你可以要求 python 打印一些行并查看所选编码是否正确。
如果你的语料库几乎完全是英文的,你可以在文件中搜索包含非 ascii 字符的行并只打印这些:
testreader = nltk.corpus.TaggedCorpusReader("filepath", r".*\.txt", encoding="Latin-1")
for line in testreader.raw(badfilename).splitlines():
if re.search(r'[\x80-\xFF]', line)):
print(line)