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

2024-10-02 18:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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() :
    f = open("olamundo.txt", "r")
    arquivo = "".join(f.readlines())
    print(colorText(arquivo))
    f.close()
    return

lertxt()

txt文件的内容是:

"Olá mundo"

报税表为:

"olá mundo"


Tags: 文件texttxtreturndefcolorblackbackground
2条回答

棒棒糖(:

只需导入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()
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')

相关问题 更多 >