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 = 0while i < len(lines):if i + 1 < len(lines) and lines[i].strip() == "python" and lines[i + 1].strip() == "Copy code":i += 2else: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)