使用 python 根据文本列表为单词着色

Coloring words based on text list using python

我有两个文本文件 d.txt 包含段落文本和 phrase.txt 包含多词短语,例如 State-of-the-art、counter productive、Fleet Dynamism 以及 [=38 中的一些=] 下面

https://en.wikipedia.org/wiki/List_of_buzzwords

如果在 phrase.txt

中找到,我需要为 d.txt 中的字体匹配短语着色

目前的努力:

phrases = open("phrase.txt").readlines()
words = open("d.txt").read()

for phrase in phrases:
    all_words_found = False
    phrase_words = phrase.lower().split(" ")
    for word in phrase_words:
        if word in words:
            all_words_found = True
            break

    if all_words_found:
        print (phrase)

预期输出:

请帮忙!

感谢帮助:

更新:创建html输出

要更改上面的代码以创建 html 输出,请在替换期间在单词周围添加一个标记而不是 ansi。这里的例子将使用一个简单的 span 标签

words = ["catch phrase", "codeword"]
phrase = "He said a catch phrase. And a codeword was written on a wall."

new_phrase = phrase
for word in words:
    new_phrase = new_phrase.replace(i, f'<span style="color:Red;">{word}</span>')
print(new_phrase) #Rather than printing, send this wherever you want it.

内联打印解决方案

但是,要回答您的基本问题,即如何用不同颜色的相同单词替换给定段落中的一组单词,请尝试使用 .replace() 和 ansi 颜色转义码。如果您想打印出 python 环境中的单词,这将起作用。

下面是一个将文本行中的某些词变成红色的简单示例:

words = ["catch phrase", "codeword"]
phrase = "He said a catch phrase. And a codeword was written on a wall."

new_phrase = phrase
for i in words:
    new_phrase = new_phrase.replace(i, f'3[91m{i}3[0;0m')
print(new_phrase)

这是另一个 Whosebug post,它讨论了 python 输出中的 ANSI 转义码和颜色:How to print colored text in Python? ANSI 转义码是一种更改输出颜色的方法 - google 它们可以找到更多 options/colors.

在此示例中,这是我使用的代码: 先把颜色改成红色:

3[91m

设置颜色后,您还必须将其改回,否则输出的其余部分也将是该颜色:

3[0;0m