如何用python中的单个空格替换文本文件中出现的多个空格


with open("test.234.txt", 'r') as f:
a=f.read()
with open("test234(double space replaced by singleones)" ,"w+") as f:
for i in range(len(a)-1):
if( a[i]+a[i+1] == "  "):
a[i].replace(a[i],"")
a[i+1].replace(a[i+1]," ")
f.write(a[i]+a[i+1])
else:
f.write(a[i])

默认分割字符串,在空格处分割字符串,忽略多个连续的空格:

with open("test.234.txt", 'r') as f:
a=f.read()
with open("test234(double space replaced by singleones)" ,"w+") as f:
for i in range(len(a)-1):
f.write(' '.join(a[i].split()))

你可以使用regex:

import re
with open("test.234.txt", 'r') as f:
with open("test234(double space replaced by singleones)" ,"w+") as out_f: 
a = f.read()
a = re.sub('s+', ' ', a))
out_f.write(a

这将打开text.txt并将所有双空格替换为一个空格。您仍然需要将b写入文本文件。你不需要一行一行地写

with open('text.txt', 'r') as f:
a = f.read()
b = a.replace("  ", " ")
print(b)

试试这个:

with open("test.234.txt", "r") as f:
a=f.readlines()

with open("test234(double space replaced by singleones)" ,"w+") as f:
for i in range(len(a)):
f.write(" ".join(a[i].split()))     
f.write("n")

我从perl开始切换到python,所以我总是在文件的每一行替换

import re
fout = open("test234(double space replaced by singleones)" ,"w+")
with open("test.234.txt", 'r') as fin:
for line in fin:
fout.write(re.sub('s+',' ',line))