我的第一个python小程序(替换文本中的标点符号为换行符)
2025-03-23 17:21:15 111 分享链接 开发笔记 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-04-06 15:46
- chrome.runtime.connect 和 chrome.runtime.onConnect 的区别
- 2025-04-06 15:44
- chrome.tabs.sendMessag chrome.runtime.sendMessage他们的区别是啥
- 2025-04-06 15:41
- Chrome 扩展 API 不同组件之间进行消息通信的监听与发送
- 2025-04-06 05:31
- 在 Chrome 扩展的 manifest.json 里,action 字段的结构在 Manifest V3 中不能使用script
- 2025-04-05 11:41
- 记录main.py调用另一个python文件的直接引用函数方法
- 2025-04-05 11:11
- 详细介绍 Python 的标准 GUI库 tkinter 中常见的组件
- 2025-04-05 01:44
- 在 tkinter 里,grid 布局与 pack布局 place布局的区别
- 2025-04-05 00:35
- 在 tkinter 里,grid 布局管理器采用 Frame 布局的原因
- 2025-04-05 00:07
- 在 tkinter 里,sticky 是 grid 布局管理器中的一个重要参数
- 2025-04-03 16:57
- JavaScript 的 MutationObserver API基础解释