python - 在 python 中突出显示句子中的特定单词

标签 python termcolor

我有一些文本,我想突出显示特定的单词。 我编写了一个脚本来遍历单词并突出显示所需的文本,但如何设置它以将其返回到句子?

from termcolor import colored

text = 'left foot right foot left foot right. Feet in the day, feet at night.'
l1 = ['foot', 'feet']
for t in text.lower().split():
    if t in l1:
        print(colored(t, 'white', 'on_red'))
    else: print(t)

在上面的例子中,我想输出两个句子,而不是所有单词的列表,并突出显示相关单词

最佳答案

使用str.join

例如:

from termcolor import colored
text='left foot right foot left foot right. Feet in the day, feet at night.'
l1=['foot','feet']
result = " ".join(colored(t,'white','on_red') if t in l1 else t for t in text.lower().split())
print(result)

关于python - 在 python 中突出显示句子中的特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57251653/

相关文章:

python - 为什么 termcolor 在 Windows 控制台中输出控制字符而不是彩色文本?

python - 我将如何在 Coding Ground 上安装 numpy 库?

python - 如何使用 termcolor 模块中的 colored 函数使字符串在指定时间内闪烁? [ python 2.7]

python - Pandas 系列箱线图未正确显示

python - 转换为 DMatrix 后 XGBoost 在训练和测试特征上的差异

python - re模块无法找到正斜杠后面的字符串

python - 在 setup.py 中包含最低 pip 版本

python - 将 pandas 数据帧插入 MySQL 表 - MySQLInterfaceError : Python type list cannot be converted