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

问题描述 投票:-1回答:2

如何创建打印语句,例如print("Hello world"),它可以是不同的颜色(例如绿色)。

而且,是否有一种方法无需下载新模块?

colors python-3.7 python-idle
2个回答
1
投票

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

它是从idlecolors发来的,由于您的访问受到限制,因此我在此处包括了idlecolors.py所需的完整模块,以使您能够轻松进行复制/粘贴,从而避免无法安装。

如您所见,唯一的依赖项是模块sysrandom,但只有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()用作随机颜色。] >

@ epicgamer300065,以下所有代码均从之前提供的@Brian和I(@Scott)链接中删除。我确实需要在导入之后立即插入init()语句以使代码正常工作,并且确实需要在命令提示符下运行此命令(但不需要管理员特权),但确实会产生预期的彩色结果。 (仅供参考,我在win10pro上使用Python 3.8.1):

from colorama import init, Fore, Back, Style
from termcolor import colored 

init() 

print(Fore.RED + 'Test')

print(Fore.RED + Back.GREEN + 'some red text') 
print(Back.GREEN + 'and with a green background') 
print(Style.BRIGHT + 'and in bright text') 
print(Style.RESET_ALL) 
print('back to normal now')

print(colored('Hello, World!', 'green', 'on_red')) 


# Python program to print 
# colored text and background 
def prRed(skk): print("\033[91m {}\033[00m" .format(skk)) 
def prGreen(skk): print("\033[92m {}\033[00m" .format(skk)) 
def prYellow(skk): print("\033[93m {}\033[00m" .format(skk)) 
def prLightPurple(skk): print("\033[94m {}\033[00m" .format(skk)) 
def prPurple(skk): print("\033[95m {}\033[00m" .format(skk)) 
def prCyan(skk): print("\033[96m {}\033[00m" .format(skk)) 
def prLightGray(skk): print("\033[97m {}\033[00m" .format(skk)) 
def prBlack(skk): print("\033[98m {}\033[00m" .format(skk)) 

prCyan("Hello World, ") 
prYellow("It's") 
prGreen("Geeks") 
prRed("For") 
prGreen("Geeks") 

# Python program to print 
# colored text and background 
class colors: 
    reset='\033[0m'
    bold='\033[01m'
    disable='\033[02m'
    underline='\033[04m'
    reverse='\033[07m'
    strikethrough='\033[09m'
    invisible='\033[08m'
    class fg: 
        black='\033[30m'
        red='\033[31m'
        green='\033[32m'
        orange='\033[33m'
        blue='\033[34m'
        purple='\033[35m'
        cyan='\033[36m'
        lightgrey='\033[37m'
        darkgrey='\033[90m'
        lightred='\033[91m'
        lightgreen='\033[92m'
        yellow='\033[93m'
        lightblue='\033[94m'
        pink='\033[95m'
        lightcyan='\033[96m'
    class bg: 
        black='\033[40m'
        red='\033[41m'
        green='\033[42m'
        orange='\033[43m'
        blue='\033[44m'
        purple='\033[45m'
        cyan='\033[46m'
        lightgrey='\033[47m'

print(colors.bg.green + colors.fg.red, "SKk", colors.bg.blue + colors.fg.red, "Amartya") 
print(colors.bg.lightgrey, "SKk", colors.fg.red, "Amartya") 


# Python program to print 
# colored text and background 
def print_format_table(): 
    """ 
    prints table of formatted text format options 
    """
    for style in range(8): 
        for fg in range(30, 38): 
            s1 = '' 
            for bg in range(40, 48): 
                format = ';'.join([str(style), str(fg), str(bg)]) 
                s1 += '\x1b[%sm %s \x1b[0m' % (format, format) 
            print(s1) 
        print('\n') 

print_format_table() 

0
投票

@ epicgamer300065,以下所有代码均从之前提供的@Brian和I(@Scott)链接中删除。我确实需要在导入之后立即插入init()语句以使代码正常工作,并且确实需要在命令提示符下运行此命令(但不需要管理员特权),但确实会产生预期的彩色结果。 (仅供参考,我在win10pro上使用Python 3.8.1):

© www.soinside.com 2019 - 2024. All rights reserved.