[英]Highlight specific words in a sentence in python
我有一些文字,我想強調具體的話。 我寫了一個腳本來循環顯示單詞並突出顯示所需的文本,但是如何設置它以將其返回到句子?
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)
您只需要將整個單詞放在列表中,然后加入空格即可
from termcolor import colored
text='left foot right foot left foot right. Feet in the day, feet at night.'
l1=['foot','feet']
formattedText = []
for t in text.lower().split():
if t in l1:
formattedText.append(colored(t,'white','on_red'))
else:
formattedText.append(t)
print(" ".join(formattedText))
結果如下:
您還可以在print()中使用end=" "
將所有內容都設為句子。
例:
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'), end=" ")
else: print(t, end=" ")
print("\n")
在我看來,你可以將你的句子分成befor循環,並嘗試如下指令。
ic = text.lower().split()
for ix, el in enumerate(ic):
if el in list_of_words:
# Run your instructions
ic[ix] = colored(el,'white','on_red'), end=" "
第二句話就是:
output = ' '.join(ic)
比@Rakesh建議的解決方案有更好的速度我建議使用:
from functools import reduce
from itertools import chain
text = 'left foot right foot left foot right. Feet in the day, feet at night.'
l1 = ['foot','feet']
print(reduce(lambda t, x: t.replace(*x), chain([text.lower()], ((t, colored(t,'white','on_red')) for t in l1))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.