Python在修改outpu后保留缩进

2024-04-25 19:08:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个解析文本文件的代码,可以修改文件,但是我需要保留缩进,请帮助我保存缩进!你知道吗

这是我的密码:

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

with open('text1238.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')

输入文本.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.

预期产量文本.txt你知道吗

 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.

如何保留压痕? 请帮我修改代码!请回答!你知道吗


Tags: andtextnameselftxtforlinegroup
2条回答

您需要替换:

groups[current_group].text.append(line)

使用:

groups[current_group].text.append('\t' + line)

这将为缩进添加制表符。或者,如果需要空格,可以使用' '(四个空格),而不是'\t'。你知道吗

问题是line = line.strip()。这将消除压痕。删除该行应该保留缩进,尽管您可能需要调整正则表达式(但不是针对显示的代码)。你知道吗

相关问题 更多 >