如何在不导入其他模块的情况下更改python中文本的颜色?

塞缪尔·梅

你怎么能创建一个打印语句,比如print("Hello world")可以是不同的颜色(例如绿色)。

另外,有没有办法在不需要下载新模块的情况下做到这一点?

斯科特

@epicgamer300065,这是一个实际的完整 IDLE 解决方案,在 win10pro 上使用 Python 3.8.1 对我有用,但它在终端中不起作用。

它来自idlecolors并且由于您的访问权限有限,我在这里包含了idlecolors.py您复制/粘贴所需的完整模块,以避免您无法安装。

如您所见,唯一的依赖项是 modulessysrandom,但random只有在必要时randcol()您可以不用功能才需要它。

这是idlecolors.py

import sys
import random

# This will only work in IDLE, it won't work from a command prompt
try:
    shell_connect = sys.stdout.shell
except AttributeError:
    print("idlecolors highlighting only works with IDLE")
    exit()

# Map the colour strings to IDLE highlighting
USE_CUSTOM_COLORS = False       # Change to True if you want to use custom colours

global colormap

if USE_CUSTOM_COLORS:
    colormap = {"red": "COMMENT",
                "orange": "KEYWORD",
                "green": "STRING",
                "blue": "stdout",
                "purple": "BUILTIN",
                "black": "SYNC",
                "brown": "console",

                "user1": "DEFINITION",
                "user2": "sel",
                "user3": "hit",
                "user4": "ERROR",
                "user5": "stderr"}
else:
    colormap = {"red": "COMMENT",
                "orange": "KEYWORD",
                "green": "STRING",
                "blue": "stdout",
                "purple": "BUILTIN",
                "black": "SYNC",
                "brown": "console"}

# ---------------------------
# Functions
# ---------------------------

# Like the print() function but will allow you to print colours
def printc(text, end="\n"):
    # Parse the text provided to find {text:color} and replace with the colour. Any text not encompassed in braces
    # will be printed as black by default.
    buff = ""
    for char in text:
        if char == "{":
            # Write current buffer in black and clear
            shell_connect.write(buff, colormap["black"])
            buff = ""
        elif char == "}":
            # Write current buffer in color specified and clear
            tag_write = buff.split(":")
            shell_connect.write(tag_write[0], tag_write[1])
            buff = ""
        else:
            # Add this char to the buffer
            buff += char

    # Write the chosen end character (defaults to newline like print)
    sys.stdout.write( end )


# Individual colour functions
def red(text):
    return "{"+ text + ":" + colormap["red"] + "}"

def orange(text):
    return "{"+ text  + ":" + colormap["orange"] + "}"

def green(text):
    return "{"+ text + ":" + colormap["green"] + "}"

def blue(text):
    return "{"+ text  + ":" + colormap["blue"] + "}"

def purple(text):
    return "{"+ text + ":" + colormap["purple"] + "}"

def black(text):
    return "{"+ text  + ":" + colormap["black"] + "}"

def brown(text):
    return "{"+ text + ":" + colormap["brown"] + "}"

def randcol(text):
    color = random.choice(list(colormap.keys()))
    return "{"+ text + ":" + colormap[color] + "}"

# User defined colours
def user1(text):
    return "{"+ text + ":" + colormap["user1"] + "}"

def user2(text):
    return "{"+ text + ":" + colormap["user2"] + "}"

def user3(text):
    return "{"+ text + ":" + colormap["user3"] + "}"

def user4(text):
    return "{"+ text + ":" + colormap["user4"] + "}"

def user5(text):
    return "{"+ text + ":" + colormap["user5"] + "}"

这是您将如何使用它:

from idlecolors import *
printc( red("Red text") )
printc( "If you add " + red("red") + " to " + blue("blue") + ", you get " + purple("purple") )

# Print a line in a random colour
printc( randcol("This is a random colour") )

# Print each word in a random colour
mytext = "This is a random piece of text which I want to print in random colours"
mytext = mytext.split(" ")
for word in mytext:
    printc(randcol(word), end=" ")

可用的颜色有red()orange()green()blue()purple()black()brown(),您可以使用randcol()此选择中的随机颜色。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在不导入的情况下检查python模块是否存在

如何在不更改其他属性的情况下更改ul中的li文本?

如何在不导入的情况下模仿Python模块?

如何在不导入模块的情况下运行模块?

如何在不更改导入的情况下将Python 3模块更改为软件包?

如何在不更改熊猫其他列的情况下对一列进行排序?

如何在不更改其他元素索引的情况下对数组中的元素进行排序?

如何在不了解路径的情况下从其他相对文件夹导入?

在Python 2中如何在不继承的情况下重用其他类的方法?

如何在不使用相对导入的情况下从另一个目录中的Python脚本执行文件(导入其他模块)?

Pygame如何在不删除其他任何内容的情况下更改背景颜色

如何在不更改其他级别顺序的情况下按一个级别对MultiIndex进行排序

我可以在不更改其他主题的情况下更改gedit的背景颜色吗?

如何在不使用导入的情况下导入导入其他模块的模块*

如何在不导入的情况下从已编译的Python模块获取函数名?

如何在不更改活动工作空间的情况下将窗口发送到其他工作空间?

如何在不更改原始模型的情况下向嵌入式文档添加其他字段

如何在不丢失格式的情况下更改文本颜色

如何在不更改其他行的情况下将 TableRow 添加到 TableLayout

如何在不扭曲该 div 中的其他对象的情况下扩展 div 并插入新文本?

如何在不更改间距或列的情况下导入和重新导出文本文件?

如何在不按 Python3 中的按钮的情况下更改 tkinter 标签的文本?

如何在不更改/删除其他工作表的情况下添加/覆盖现有 xlsx 文件的工作表

如何在不更改框阴影颜色的情况下更改 svg 颜色

rollup.js 如何在不更改源文件的情况下导入其他文件

如何在不更改 python matplotlib 中的热图的情况下更改颜色条的值?

如何在不更改其他行的情况下将页脚放在网格底部?

如何在不区分文件的情况下制作 Python 包,即其他类型

如何在不更改文本颜色本身的情况下更改输入字段中打字机的颜色?