將 txt 文件中所有中文逗號「,」替換為空格,保持詞語間距離。
def replace_comma(filepath):
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
content = content.replace(',', ' ') # 替換中文逗號
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
replace_comma('data.txt')
with open 自動管理文件關閉。str.replace(old, new) 全局替換。encoding='utf-8' 避免中文亂碼。