gpt4 book ai didi

Python在修改输出后保留缩进

转载 作者:行者123 更新时间:2023-12-01 05:04:23 25 4
gpt4 key购买 nike

我有一个解析文本文件并修改文件的代码,但我需要保留缩进请帮助我实现保留的缩进!

这是我的代码:

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.

如何保留缩进?请帮助我修复我的代码!我们将不胜感激!

最佳答案

问题是line = line.strip()。这将删除缩进。删除该行应该保留缩进,尽管您可能需要调整正则表达式(但不适用于所示的代码)。

关于Python在修改输出后保留缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com