假设我们有一个包含以下内容的文件:
{{{banana},{kinky},{bronze-spaghetti,
definitly-not},{legitimate-style, witness,
drunk}}}
我想重新安排此文件,使其如下所示:
{{{banana},
{kinky},
{bronze-spaghetti,definitly-not},
{legitimate-style, witness, drunk}}}
请注意,除最后一行外,每行以},
结尾。现在我的问题是我该怎么做?
答案 0 :(得分:2)
你可以找到正则表达式“},”并在其后插入一个新行
编辑: 正如jDo建议的那样,你可以这样做:
with open('in.txt', 'r') as infile:
data=infile.read()
with open('out.txt', 'w') as outfile:
outfile.write(data.replace("\n", "").replace("},", "},\n"))
答案 1 :(得分:1)
我认为你可以简单地使用replace
(多行字符串的三重引号):
original_text = """{{{banana},{kinky},{bronze-spaghetti, definitly-not},{legitimate-style, witness, drunk}}}"""
reformatted = original_text.replace("\n", "").replace("},", "},\n")
print(reformatted)
这可以在shell中轻松完成:
>>> my_str = """{{{banana},{kinky},{bronze-spaghetti,
... definitly-not},{legitimate-style, witness,
... drunk}}}"""
>>>
>>> my_str = my_str.replace("\n", "").replace("},", "},\n")
>>>
>>> print(my_str)
{{{banana},
{kinky},
{bronze-spaghetti,definitly-not},
{legitimate-style, witness,drunk}}}
>>>