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

How do I replace multiple blank spaces occuring in a text file with a single space in 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()))

您可以使用正则表达式:

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

我从 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))

这将打开 text.txt 并将所有双 space 替换为单个 space。您仍然需要将 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")