【问题标题】:Finding the broken file in a corpus Python在语料库 Python 中查找损坏的文件
【发布时间】:2015-11-18 19:01:25
【问题描述】:

我正在使用 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:无效的起始字节

【问题讨论】:

  • 你能把你的输入文件贴在某个地方吗,我们可以帮你检查它是否是编码问题。你也在 python3 上吗?
  • @alvas 我做了更多的挖掘,问题是文件没有以 utf-8 编码。我正在使用 Python 3。

标签: python nltk corpus


【解决方案1】:

您可以通过一次读取一个文件来识别文件,如下所示:

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)

【讨论】:

  • 这正是我需要的,谢谢!我找到了有问题的文件并将它们的编码更改为 utf-8 并解决了问题。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多