【发布时间】: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