以下是一个示例脚本:
import redef clean_file(input_file, output_file):# 读取文件内容with open(input_file, 'r', encoding='utf-8') as file:content = file.read()# 使用正则表达式删除 ### ** 和 ---cleaned_content = re.sub(r'### \*\*|---+', '', content)# 将清理后的内容写入新文件with open(output_file, 'w', encoding='utf-8') as file:file.write(cleaned_content)print(f"清理后的内容已保存到 {output_file}")# 示例用法
input_file = 'input.txt' # 输入文件名
output_file = 'output.txt' # 输出文件名
clean_file(input_file, output_file)
脚本说明:
re.sub
:使用正则表达式替换功能,删除### **
和---
。r'### \*\*|---+'
:匹配### **
或任意数量的-
(---+
)。
- 输入文件:
input.txt
是你要清理的文件。 - 输出文件:
output.txt
是清理后的文件。
示例:
假设 input.txt
内容如下:
### ** 标题1 **
---
内容1
### ** 标题2 **
---
内容2
运行脚本后,output.txt
内容将变为:
标题1
内容1标题2
内容2
注意事项:
- 如果
### **
或---
是单独一行,删除后可能会留下空行。如果需要删除空行,可以在脚本中添加额外的处理逻辑。 - 确保文件路径正确,脚本和文件在同一目录下,或者提供完整路径。