【问题标题】:How to read a utf-8 encoded text file using Python如何使用 Python 读取 utf-8 编码的文本文件
【发布时间】:2016-12-01 19:06:33
【问题描述】:

我需要分析一个泰米尔语文本文件(utf-8 编码)。我在接口 IDLE 上使用 Python 的 nltk 包。当我尝试读取界面上的文本文件时,这是我得到的错误。如何避免这种情况?

corpus = open('C:\\Users\\Customer\\Desktop\\DISSERTATION\\ettuthokai.txt').read()

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    corpus = open('C:\\Users\\Customer\\Desktop\\DISSERTATION\\ettuthokai.txt').read()
  File "C:\Users\Customer\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 33: character maps to <undefined>

【问题讨论】:

  • 我还没有完全阅读您的问题,但是...如果您有大量字节,您可以使用 your_bytes.decode("UTF-8") 将它们解码为字符串。
  • 哪个 Python 版本?
  • @AntonisChristofides - 从回溯中,我推断出 Python3。

标签: python encoding utf-8


【解决方案1】:

由于您使用的是 Python 3,只需将 encoding 参数添加到 open()

corpus = open(
    r"C:\Users\Customer\Desktop\DISSERTATION\ettuthokai.txt", encoding="utf-8"
).read()

【讨论】:

  • 仅适用于 Python 3+。对于 Python 2,请使用 codecs.open
猜你喜欢
  • 1970-01-01
  • 2013-07-04
  • 2016-08-14
  • 2011-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-13
  • 2015-08-13
相关资源
最近更新 更多