如何将文本文件中的字符串转换为 unicode?
How do I turn a string into a unicode from a text file?
我有一个包含以下内容的文本文件:
Guadalajara
Culiacán
Juárez
Ecatepec
我想将所有这些都转换为 unicode。我尝试使用:
unicode(INSERT WORD FROM TEXT FILE)
但是我得到错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 6: ordinal not in range(128)
有没有办法将字符串从文本文件转换为 unicode?
您需要知道文件的编码。如果这样做,请使用 codecs.open()
打开文件,您将自动获得正确的 Unicode 对象:
import codecs
with codecs.open("myfile.txt", encoding="utf-8") as infile:
text = infile.read()
您也可以打开文件 "normally",然后手动解码其内容 - 但您仍然需要知道编码是什么:
with open("myfile.txt") as infile:
text = infile.read()
uni = text.decode("utf-8")
我有一个包含以下内容的文本文件:
Guadalajara
Culiacán
Juárez
Ecatepec
我想将所有这些都转换为 unicode。我尝试使用:
unicode(INSERT WORD FROM TEXT FILE)
但是我得到错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 6: ordinal not in range(128)
有没有办法将字符串从文本文件转换为 unicode?
您需要知道文件的编码。如果这样做,请使用 codecs.open()
打开文件,您将自动获得正确的 Unicode 对象:
import codecs
with codecs.open("myfile.txt", encoding="utf-8") as infile:
text = infile.read()
您也可以打开文件 "normally",然后手动解码其内容 - 但您仍然需要知道编码是什么:
with open("myfile.txt") as infile:
text = infile.read()
uni = text.decode("utf-8")