如何在使用Python中的函数后以正确的编码读取txt文件

如何在使用Python中的函数后以正确的编码读取txt文件,python,python-3.x,Python,Python 3.x,我试图读取一个txt文件,使用一个函数来显示终端中的颜色,但由于我这样做,文件中所有的重音单词都变得一团糟。。如何用正确的编码显示彩色的txt文件 颜色={\ “黑色”:“\u001b[30;1m”, “粗体”:“\u001b[1m”, “重置”:“\u001b[0m”, “红色”:“\u001b[31;1m”, “绿色”:“\u001b[32m”, “黄色”:“\u001b[33;1m”, “蓝色”:“\u001b[34;1m”, “洋红”:“\u001b[35m”, “青色”:“\u001b

我试图读取一个txt文件,使用一个函数来显示终端中的颜色,但由于我这样做,文件中所有的重音单词都变得一团糟。。如何用正确的编码显示彩色的txt文件

颜色={\
“黑色”:“\u001b[30;1m”,
“粗体”:“\u001b[1m”,
“重置”:“\u001b[0m”,
“红色”:“\u001b[31;1m”,
“绿色”:“\u001b[32m”,
“黄色”:“\u001b[33;1m”,
“蓝色”:“\u001b[34;1m”,
“洋红”:“\u001b[35m”,
“青色”:“\u001b[36m”,
“白色”:“\u001b[37m”,
“棕色”:“\u001b[94m”,
“黄色背景”:“\u001b[43m”,
“黑色背景”:“\u001b[40m”,
“青色背景”:“\u001b[46;1m”,
}
def colorText(文本):
对于颜色中的颜色:
text=text。替换(“[[”+颜色+“]]”,颜色[颜色])
返回文本
def lertxt():
f=打开(“olamundo.txt”,“r”)
arquivo=“”.join(f.readlines())
打印(彩色文本(arquivo))
f、 关闭()
回来
lertxt()
txt文件的内容是:

“奥拉蒙多”

报税表为:

“蒙多”

棒棒糖(:

只需导入io,然后:

import io

COLORS = {\
"black":"\u001b[30;1m",
"bold":"\u001b[1m",
"reset":"\u001b[0m",
"red": "\u001b[31;1m",
"green":"\u001b[32m",
"yellow":"\u001b[33;1m",
"blue":"\u001b[34;1m",
"magenta":"\u001b[35m",
"cyan": "\u001b[36m",
"white":"\u001b[37m",
"brown":"\u001b[94m",
"yellow-background":"\u001b[43m",
"black-background":"\u001b[40m",
"cyan-background":"\u001b[46;1m",
}

def colorText(text):
    for color in COLORS:
        text = text.replace("[[" + color + "]]", COLORS[color])
    return text

def lertxt() :
    with io.open("olamundo.txt", "r", encoding="utf8") as f:
        text = f.read()
    print(colorText(text))
    f.close()
    return

lertxt()

“”.join(f.readlines())
f.read()
一样不起作用……不幸的是,我认为当函数colorText在打开后被调用时会出现错误的编码,这里:
print(colorText(arquivo))
它确实起作用。已经测试过了。我将用完整的代码编辑我的答案(:
First of all you should use like this arquivo = " ".join(f.readlines())
otherwise there won't be spaces a the string gets messed up.

you should use encoding: 
open("olamundo.txt", 'r', encoding='utf8')