我有一个看起来像这样的文本文件:
XX number number number
XY number number number
...
XN number number number
XX,XY等有1个或2个字符,数字可以是正数也可以是负数,它并不重要。我想弄清楚的是(但我不能,对于我的生活)是如何在XX,XY等之后插入换行符,以便我的文件看起来像这样:
XX
number number number
XY
number number number
...
XN
number number number
我还想做的是删除每个XX,XY之后的空格,但不删除数字之间的空格。我到目前为止所尝试的所有内容仅在每2个字符后引入换行符。我是Python的超级初学者,所以任何帮助都会受到赞赏。
答案 0 :(得分:2)
str.replace()
似乎是一个不错的选择,特别是如果你想修改每一行。
with open('input.txt') as input_file:
with open('output.txt', 'w') as output_file:
for line in input_file:
line = line.replace(' ', '\n', 1)
output_file.write(line)
如果您只想修改某些行, re.sub()
将是一个不错的选择,并且可以使用正则表达式选择要修改的行:
import re
with open('input.txt') as input_file:
with open('output.txt', 'w') as output_file:
for line in input_file:
line = re.sub(r'(^[A-Z]+)\s+', r'\1\n', line)
output_file.write(line)
str.split()
也可能有效,但它会破坏数字之间的任何多个空格序列:
with open('input.txt') as input_file:
with open('output.txt', 'w') as output_file:
for line in input_file:
line = line.split()
output_file.write(line[0] + '\n')
output_file.write(' '.join(line[1:]) + '\n')
答案 1 :(得分:0)
import re
with open('input.txt') as input_file:
with open('output.txt', 'w') as output_file:
for line in input_file:
splitter = re.search("\d", line).start()
output_file.write(line[:splitter].strip() + "\n")
output_file.write(line[splitter:])