gpt4 book ai didi

python - 使用python基于文本列表着色单词

转载 作者:行者123 更新时间:2023-12-04 03:55:50 25 4
gpt4 key购买 nike

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

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)

预期输出: enter image description here

请帮忙!

感谢您的帮助:

最佳答案

更新:创建 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'\033[91m{i}\033[0;0m')
print(new_phrase)

这是另一个 stackoverflow 帖子,它讨论了 Python 输出中的 ANSI 转义码和颜色:How to print colored text in Python?ANSI 转义码是一种更改输出颜色的方法 - 用谷歌搜索它们可以找到更多选项/颜色。

在这个例子中,这里是我使用的代码:首先将颜色更改为红色:

\033[91m

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

\033[0;0m

关于python - 使用python基于文本列表着色单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63929659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com