使用python对基于文本列表的单词进行着色

使用python对基于文本列表的单词进行着色,python,pandas,nltk,Python,Pandas,Nltk,我得到了两个文本文件d.txt,其中包含段落文本和短语。txt包含多词短语,如最新技术、适得其反、快速动态以及下面链接中的一些短语 如果在phrase.txt中找到,我需要为d.txt中的字体匹配短语添加颜色 迄今为止的努力: phrases = open("phrase.txt").readlines() words = open("d.txt").read() for phrase in phrases: all_words_found =

我得到了两个文本文件d.txt,其中包含段落文本和短语。txt包含多词短语,如最新技术、适得其反、快速动态以及下面链接中的一些短语

如果在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输出,请在replace期间而不是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.
下面是另一篇stackoverflow文章,讨论python输出中的ANSI转义码和颜色: ANSI转义码是更改输出颜色的一种方法-通过谷歌搜索它们来查找更多选项/颜色

在此示例中,我使用了以下代码: 首先要将颜色更改为红色:

\033[91m
设置颜色后,还必须将其更改回原色,否则输出的其余部分也将是该颜色:

\033[0;0m

该文本将如何显示?在html文档中?我会问与MVB76相同的问题-您想要什么输出?如果您想在python中打印,请查看ansi颜色转义码。我想将其作为HTML输出。对不起,我应该提到它。如果你想要HTML输出,只需将每个短语替换为表示你想要的颜色变化的HTML标记,而不是使用ansi转义码。我将用一个例子更新我的答案。我个人想在我的大项目中创建一个css类并应用它,但对于这个例子,我只想作为一个短语
\033[0;0m