【问题标题】:Highlight specific words in a sentence in python在python中突出显示句子中的特定单词
【发布时间】:2019-12-06 15:57:18
【问题描述】:

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

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)

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

【问题讨论】:

    标签: python termcolor


    【解决方案1】:

    使用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)
    

    【讨论】:

    • 嗨@Rakesh - 你能指导一下如何在一个完整的短语中实现这个精确的结果,而不必单独砍掉单词吗?
    【解决方案2】:

    你只需要将整个单词放在一个列表中,然后用空格连接

    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))
    

    结果如下:

    【讨论】:

      【解决方案3】:

      您还可以在 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")
      

      【讨论】:

        【解决方案4】:

        在我看来,您可以在循环之前拆分句子,然后尝试如下指令。

        
        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)
        
        

        【讨论】:

          【解决方案5】:

          为了获得比@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)))) 
          

          还有表演:

          【讨论】:

            猜你喜欢
            • 2019-06-24
            • 2014-03-08
            • 2021-06-28
            • 2020-10-11
            • 1970-01-01
            • 2015-01-10
            • 2017-09-10
            • 2017-08-29
            • 2012-01-29
            相关资源
            最近更新 更多