要标记包含特定字符串的行,可以使用以下示例代码:
def mark_lines(file_path, keyword):
    with open(file_path, 'r') as file:
        lines = file.readlines()
    marked_lines = []
    for i, line in enumerate(lines):
        if keyword in line:
            marked_lines.append(i + 1)  # 添加行号到结果列表
    return marked_lines
file_path = 'example.txt'  # 你的文件路径
keyword = 'example'  # 要搜索的关键字
marked_lines = mark_lines(file_path, keyword)
print(f"The keyword '{keyword}' is found in the following lines:")
for line_number in marked_lines:
    print(f"Line {line_number}: {lines[line_number - 1]}")
在上面的示例中,mark_lines函数接受文件路径和要搜索的关键字作为参数。它打开文件,逐行读取文件内容,并将包含关键字的行的行号添加到marked_lines列表中。最后,打印出包含关键字的行号和行内容。
你需要将file_path变量设置为你要搜索的文件的路径,将keyword变量设置为你要搜索的关键字。然后运行代码,它将打印出包含关键字的行号和行内容。
下一篇:标记本季度的最后一天