PYTHON从文本中查找并同时删除相邻二行的特定文字

PYTHON从文本中查找并同时删除相邻二行的特定文字
例如同时删除上下行文字:
python
Copy code

def remove__code(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    with open(output_file, 'w', encoding='utf-8') as file:
        i = 0
        while i < len(lines):
            if i + 1 < len(lines) and lines[i].strip() == "python" and lines[i + 1].strip() == "Copy code":
                i += 2
            else:
                file.write(lines[i])
                i += 1
remove__code('netProgram.txt', 'netProgram_news.txt')

删除相邻重复行中的一行:

def remove_adjacent_duplicates(input_text):
    lines = input_text.split('\n')
    output_lines = []

    for i in range(len(lines)):
        if i == 0 or lines[i] != lines[i - 1]:
            output_lines.append(lines[i])

    return '\n'.join(output_lines)


if __name__ == "__main__":
    input_text = """Hello
Hello
World
World
Python
Python
"""

    output_text = remove_adjacent_duplicates(input_text)
    print(output_text)

你可能感兴趣的:(java,前端,linux,python,开发语言)