python - 如何删除每行中的多个空格并替换为单个空格?
问题描述
我是脚本新手,我试图删除一行中的多个空格并将其替换为一个空格。
输入.txt
Hello world
Welcome to python
输出应该像
Hello world
Welcome to python
我按照以下命令
with open ('input.txt', 'r') as i_f, open ('output.txt', 'w') as o_f:
for line in i_f:
o_f.write(re.sub('\s+',' ', line))
我的输出类似于
Hello world Welcome to python
我正在尝试用每行的一个空格替换多个空格。我不想将多行合并为一行。谁能帮我删除多个空格并通过不加入行来用单个空格替换它们。任何帮助,将不胜感激。提前致谢。
解决方案
您的问题是由匹配任何空白字符的事实引起的\s
,并且每行末尾的换行符都算作空白。
由于 Python 中没有除换行符之外的空白字符的简写字符,因此您需要明确列出要匹配的空白字符:
with open ('input.txt', 'r') as i_f, open ('output.txt', 'w') as o_f:
for line in i_f:
# Match only tabs and spaces
o_f.write(re.sub('[\t ]+',' ', line))
如果您要使用正则表达式,我强烈推荐本教程。太棒了。
推荐阅读
- amazon-cloudformation - 如何在 cloudformation 中转义 $ 符号
- sql - 使用 OR 与 ColdFusion 过滤 SQL 查询 Where 子句?
- cassandra - 数据模型:多主键的 Cassandra 表
- c# - 如何使用 IXmlSerializable 更改根元素的名称?
- linux - 使用 awk/sed/cut/grep 从文本文件中提取冒号分隔的字段/值
- youtube - Youtube 直播嵌入代码显示“直播离线”
- go - Golang Cronjob vs time.Ticker 用例
- node.js - Cloud9 数据库到 mLab 数据库“失败:连接到数据库服务器时出错:没有可访问的服务器”
- python - 我的 if 语句在 python 中不起作用
- javascript - 通过单选按钮的值控制 textarea 的元素属性