首页 > 解决方案 > 如何更改句子中的文本颜色?

问题描述

我的代码:

from functools import partial

def x_in_y(word, inner):
    return inner in word

words = [
    ('mann', 'men'),
    ('connaction', 'connection'),
    ('tee', 'tea'),
    ('rigt', 'right'),
    ('putt', 'putt'),
    ('yewrwe','tyte')
]

sentence=['this mann is my son','the connaction is unstable','my tee is getting cold','put your hands down','rigt now','right behind my back']

for wrong,correct in words:
    filtered_names = filter(partial(x_in_y, inner=wrong), sentence)
    next_elem = next(filtered_names, None)
    if next_elem:
        print(f"Typo: {wrong} 'should be {correct}'")
        print(next_elem)
    for name in filtered_names:
        print(name)

输出:

Typo: mann 'should be men'
this mann is my son
Typo: connaction 'should be connection'
the connaction is unstable
Typo: tee 'should be tea'
my tee is getting cold
Typo: rigt 'should be right'
rigt now

我希望只更改错字的文本颜色。

像这样:

Typo: mann 'should be men'
this →mann←red  is my son
Typo: connaction 'should be connection'
the →connaction←red is unstable
Typo: tee 'should be tea'
my →tee←red is getting cold
Typo: rigt 'should be right'
→rigt←red now

怎么做?我只能改变整个句子的颜色。我不知道如何只更改部分文本。我应该使用str.replace函数还是什么?

任何人都可以帮助我或给我一个线索吗?

标签: pythonpython-3.x

解决方案


是的,您可以使用.replace, 用单词pluswrong的 ANSI 转义序列替换单词来打印彩色终端文本。correct colorama

代码:

from colorama import init, Fore, Style
init()

...

for wrong, correct in words:
    ...
    if next_elem:
        print(f"Typo: {wrong} 'should be {correct}'")
        print(next_elem.replace(wrong, f"{Fore.RED}{wrong}{Style.RESET_ALL}"))
    ...

输出:

在此处输入图像描述


推荐阅读