python - 如何使用 Python 读取 utf-8 编码的文本文件

标签 python encoding utf-8

我需要分析泰米尔语(utf-8 编码)的文本文件。我在 IDLE 接口(interface)上使用 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>

最佳答案

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

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

关于python - 如何使用 Python 读取 utf-8 编码的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40918503/

相关文章:

oracle - 有没有办法在配置为 'US7ASCII' 的 Oracle 数据库中存储 Unicode 文本

java - 如何在java中通过FTP编写 "UTF-16"编码文件

python - Pandas - 在数据框中找不到列

c - 如何转换UTF-8字符串?

python - 对于新安装的模块,如何让 `ipython` import autocomplete 起作用?

python - 切片正在向我的阵列添加第三维 - 不知道为什么

python - 如何在 Odoo 12v 中从销售订单、发票、采购订单、账单等 PDF 报告的第二页中删除页眉和页脚

Python - 解析 XML 时遇到问题

python - 当某些字符串具有 UTF-8 字符时,pandas DataFrame.style.render

swift - Swift 中字符串操作的复杂性