python - 如何更改句子中的文本颜色?
问题描述
我的代码:
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
函数还是什么?
任何人都可以帮助我或给我一个线索吗?
解决方案
是的,您可以使用.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}"))
...
输出:
推荐阅读
- sql-server - 数据库超过 40000 行,单库 vs 两库哪个更好?
- oracle - 循环传递多个值
- spring - 在 RequestMethod.GET 函数上获取 HttpMediaTypeNotAcceptableException
- python - 在所有 excel 行中运行的 Python 脚本
- android - Hilt Fragment 必须附加到@AndroidEntryPoint Activity,同时测试(它附加到@AndEntPoint 标记的活动)
- sql-server - 如何在截断表的存储过程中包含表名?
- python - 未安装 cv 如何解决以下错误?
- python - matplotlib中子图之间的垂直分隔符
- python - 在散点图中保持恒定的网格线
- bash - 从磁盘映像文件挂载多个分区