Python在写入文件时保留缩进

0 投票
2 回答
2175 浏览
提问于 2025-04-18 18:22

我有一段Python代码,它可以把括号里相同的词汇归在一起,并把剩下的文本合并起来。但是问题是,它在写入时没有保留原来的缩进。

我的代码:

import re
import collections
class Group:
    def __init__(self):
        self.members = []
        self.text = []

with open('text.txt','r+') as f:
    groups = collections.defaultdict(Group)
    group_pattern = re.compile(r'^(\S+)\((.*)\)$')
    current_group = None
    for line in f:
        line = line.strip()
        m = group_pattern.match(line)
        if m:    # this is a group definition line
            group_name, group_members = m.groups()
            groups[group_name].members += filter(lambda x: x not in groups[group_name].members , group_members.split(','))
            current_group = group_name
        else:
            if (current_group is not None) and (len(line) > 0):
                groups[current_group].text.append(line)
    f.seek(0)
    f.truncate()

    for group_name, group in groups.items():
        f.write("%s(%s)" % (group_name, ','.join(group.members)))
        f.write( '\n'.join(group.text) + '\n')

文本文件:text.txt

  Car(skoda,audi,benz,bmw)
    The above mentioned cars are sedan type and gives long rides efficient
 ......

  Car(Rangerover,audi,Hummer)
SUV cars are used for family time and spacious.

期望的输出:

  Car(skoda,audi,benz,bmw,Rangerover,Hummer)
    The above mentioned cars are sedan type and gives long rides efficient
 ......
SUV cars are used for family time and spacious.

但实际得到的是:

Car(skoda,audi,benz,bmw,Rangerover,Hummer)The above mentioned cars are sedan type and gives long rides efficient
 ......
SUV cars are used for family time and spacious.

2 个回答

0

你的问题出在你写这些行之前的格式处理上。

import re
import collections
class Group:
    def __init__(self):
        self.members = []
        self.text = []

with open('text.txt','r+') as f:
    groups = collections.defaultdict(Group)
    group_pattern = re.compile(r'^(\S+)\((.*)\)$')
    current_group = None
    for line in f:
        m = group_pattern.match(line)
        if m:    # this is a group definition line
            group_name, group_members = m.groups()
            groups[group_name].members += filter(lambda x: x not in groups[group_name].members , group_members.split(','))
            current_group = group_name
        else:
            if (current_group is not None) and (len(line) > 0):
                groups[current_group].text.append(line)

    with open("text.txt","w") as f:
        for group_name, group in groups.items():
            f.write("%s(%s)" % (group_name, ','.join(group.members)))
            f.write("\n")
            f.write( ''.join(group.text))
            f.write("\n")
0

你正在用这一行代码去掉字符串开头和结尾的空白字符:

line = line.strip()

撰写回答