我正在文本文件中搜索单词。它找到单词并返回包含该单词的行。这很好,但我想在该行中突出显示或加粗该词。
我可以在 Python 中执行此操作吗?我也可以使用更好的方法来获取用户 txt 文件路径。
def read_file(file):
#reads in the file and print the lines that have searched word.
file_name = raw_input("Enter the .txt file path: ")
with open(file_name) as f:
the_word = raw_input("Enter the word you are searching for: ")
print ""
for line in f:
if the_word in line:
print line
最佳答案
注意:这仅适用于控制台。您不能为纯文本文件中的文本着色。这就是它被称为纯文本的原因。
特殊字符的一种格式是 \033[(NUMBER)(NUMBER);(NUMBER)(NUMBER);...m
第一个数字可以是 0、1、2、3 或 4。对于颜色,我们只使用 3 和 4。3 表示前景色,4 表示背景色。第二个数字是颜色:
0 black
1 red
2 green
3 yellow
4 blue
5 magenta
6 cyan
7 white
9 default
因此,要打印“Hello World!”对于蓝色背景和黄色前景,我们可以执行以下操作:
print("\033[44;33mHello World!\033[m")
无论何时开始使用一种颜色,您都希望重置为默认值。这就是 \033[m
所做的。
关于python - 如何在文本文件中找到 "highlight"一个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35731194/