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