Python如何移除文件内容中行内冒号、逗号后的多余空格
问题原因
你原有代码仅调用了strip()方法,该方法只会移除字符串首尾的空白字符,完全不会处理行中间冒号、逗号后带的空格,因此无法实现预期效果。
实现方案
方案1:确定符号后仅带单个空格(写法最简单)
直接使用两次替换操作即可:
import os file_path = os.path.join(os.path.expanduser('~'), 'test_alerts') cleaned_lines = [] with open(file_path, 'r', encoding='utf-8') as f: for line in f: stripped_line = line.strip() if not stripped_line: continue # 依次替换逗号、冒号后的空格 cleaned_line = stripped_line.replace(', ', ',').replace(': ', ':') cleaned_lines.append(cleaned_line) # 打印处理后的内容 print(cleaned_line) # 若需要将处理结果写回原文件,放开下方注释即可 # with open(file_path, 'w', encoding='utf-8') as f: # f.write('\n'.join(cleaned_lines))
方案2:适配符号后带多个空格的场景(通用性更强)
用正则匹配替换所有冒号、逗号后的任意数量空白字符:
import os import re file_path = os.path.join(os.path.expanduser('~'), 'test_alerts') cleaned_lines = [] with open(file_path, 'r', encoding='utf-8') as f: for line in f: stripped_line = line.strip() if not stripped_line: continue # 匹配冒号/逗号后跟着的1个及以上空白字符,替换为空 cleaned_line = re.sub(r'([:,])\s+', r'\1', stripped_line) cleaned_lines.append(cleaned_line) print(cleaned_line) # 写回原文件的代码同方案1
处理效果
你提供的样例内容处理后输出如下:
"test-everything"|["messages,kubelet.service"]|[{"triggerinterval":"12h","triggerlimit":1,"integration":"email","immediate":false,"terminal":true,"operator":"presence","emails":["fun@us.com"]}]|"3fddf26cb4"
内容的提问来源于stack exchange,提问作者yugreddy
相关产品推荐
相关产品推荐

