【问题标题】:Text file encoded in utf-8, Python giving UnicodeDecodeError, ignore errors not working以 utf-8 编码的文本文件,Python 给出 UnicodeDecodeError,忽略错误不起作用
【发布时间】:2018-11-22 22:25:56
【问题描述】:

我正在尝试读入以 utf-8 编码的“CDPQ17CEO.txt”,请看这张图片: Notepad++ Encoding

这里是 read_in 函数(在 Letter 类中):

class Letter(object):

def __init__(self, file_path, company_name, author_name=None, author_type = None):
   self.letter = self._read_in(file_path)
   self.company = company_name
   self.author = author_name
   self.type = author_type

def _read_in(self, file_path):
    f = open(file_path, 'r', encoding='utf-8', errors='ignore').readlines()
    f_stripped = [line.strip() for line in f]
    f.close()
    return ' '.join(f_stripped)

这里是函数调用:

full_file = 'Q:\My Documents\OTPP\letters\CDPQ17CEO.txt'    
letter_dict[name]=px.Letter(full_file, name, author_type=author_type)

这是错误:

UnicodeDecodeError:“charmap”编解码器无法解码位置 1936 中的字节 0x9d:字符映射到未定义>

为什么 errors = 'ignore' 没有发挥作用?

如果我打开文本文档并将其转换为 ANSI,重新保存并重新运行,这确实有效,但我宁愿避免对我需要读入的所有文档执行此操作。

谢谢!

【问题讨论】:

  • 显然对px.Letter 的调用不会调用您在此处显示的方法。 “charmap 编解码器”建议使用 open 函数而不指定 encoding 参数,这需要使用特定于平台的默认编解码器(通常是一些本地化的 Windows 代码页,有时在窗户)。
  • 嗯。我在类定义中添加了可能使其更清晰的内容。我不明白它如何调用不同的方法。有什么想法吗?
  • 错误的回溯是否告诉您UnicodeDecodeError 发生在哪一行?
  • 这一行:f = open(file_path, 'r', encoding='utf-8', errors='ignore').readlines()
  • 这意味着encoding= 参数被忽略。这是 Python 3 内置的 open 函数吗?

标签: python utf-8 built-in python-unicode


【解决方案1】:

问题及解决方案:

  • 包含 Letter 类的 px 模块实际上并未导入,尽管它似乎是
  • 通过将模块的路径添加到 PYTHONPATH 解决了问题

    import sys
    sys.path.append('foo')
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多