我有一个文本文件,如下所示:
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的超级初学者,如果有任何帮助,我将不胜感激。
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'1n', 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')
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:])