简体   繁体   English

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

[英]How to read a txt file with the correct encoding after using a function in Python

Im trying to read a txt file using a function to show colors in terminal but since i do this all the accented words in file get a mess.. How to show the txt file colored and with the correct encoding?我正在尝试使用函数读取 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()

content of the txt file is: txt文件的内容是:

"Olá mundo" 《奥拉世界》

the return is:回报是:

"olá mundo" “olámundo”

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')

Lolip (:棒棒糖 (:

Just import io and, then:只需导入 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM