如何“突出显示”在文本文件中找到的单词?

新手上路,请多包涵

我正在一个文本文件中搜索一个词。它找到单词并返回包含该单词的行。这很好,但我想在该行中突出显示或加粗该词。

我可以在 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

原文由 jeffkrop 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 497
1 个回答

注意:这仅适用于控制台。您不能为纯文本文件中的文本着色。这就是为什么它被称为 文本。

特殊字符的一种格式是 \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 所做的。

原文由 zondo 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题