我的第一个python小程序(替换文本中的标点符号为换行符)
2025-03-23 17:21:15 258 分享链接 开发笔记 python
import string
# 合并中文和英文标点符号
punctuations = string.punctuation + '!?。。,、;:“”‘’()〔〕【】﹃﹄「」﹁﹂—…-~《》〈〉'
def remove_punctuation_and_newline(text):
result = ""
for char in text:
if char in punctuations:
result += '\n'
else:
result += char
# 去除多余的空行
result = '\n'.join(line.strip() for line in result.split('\n') if line.strip())
return result
if __name__ == "__main__":
try:
# 读取文件
with open('a.txt', 'r', encoding='utf-8') as file:
input_text = file.read()
# 去除标点符号并换行
output_text = remove_punctuation_and_newline(input_text)
# 将结果写入新文件
with open('output.txt', 'w', encoding='utf-8') as output_file:
output_file.write(output_text)
print("处理完成,结果已保存到 output.txt 文件中。")
except FileNotFoundError:
print("错误:未找到 a.txt 文件,请检查文件路径和文件名。")
except Exception as e:
print(f"发生未知错误:{e}")
最近更新
- 2025-08-04 16:13
- 详细介绍一下 tkinter 的pack布局参数
- 2025-08-03 17:50
- pyinstaller --onefile --windowed 与 pyinstaller -F -w的区别
- 2025-08-03 17:39
- 使用 PyInstaller 打包 Python 程序时 隐藏调用其它程序的命令窗口。
- 2025-08-03 11:04
- 使用 PyInstaller 打包 Python 程序时 -F 与 -D的区别。
- 2025-08-01 15:15
- 通过Edge-tts生成的中文字幕如何自然断句?
- 2025-07-31 18:23
- Edge-tts库 命令行工具有哪些常用参数?
- 2025-07-29 01:43
- 豆包连环画生成提示(优化版)
- 2025-07-28 13:20
- 镜头运动手法:不止推拉,这些技巧让画面更有张力。
- 2025-07-28 13:13
- 摄影与剪辑是视频创作的两个核心环节,二者共同决定了作品的最终呈现效果。
- 2025-07-23 16:35
- 在Python中如何获取脚本所在的目录?