python - 如何在文本文件中找到 "highlight"一个单词?

标签 python

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

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

相关文章:

python - 通过 gobject.timeout_add 回调函数用 cairo 绘制一个点

python - 基于列值的 Pandas 重新索引任务

python - 从列表元素形成字典

python - 如何在 MySQL 表行中存储多个用户

python - 如何控制 lxml xpath text() 函数中的换行处理?

Python + 二维数组切片 + valueerror : operands could not be broadcast together

python - numpy 数组 : efficient way to compute argmax within a fixed window at a set of rows and columns given as input

python - 为什么 pip 不适合我?

python - 来自太阳的运动检测照明

python - 以相反顺序打印列表不起作用 - Python 3x