我写了一个Python脚本来捕获我想要的数据,但是 我有一个包含多个段落的结果文本文件,但每个段落都由不同的空行分隔 - 从 2 到 8 个。
我的文件末尾还有多个空行。
我希望Python在段落之间留下不超过2个空行,并且在文本文件末尾不留空行。
我尝试过循环和 line.strip、替换等,但我显然不知道如何将它们组合在一起。
到目前为止我一直在使用的示例
wf = open(FILE,"w+")
for line in wf:
newline = line.strip('^\r\n')
wf.write(newline)
wf.write('\n')
最佳答案
实际上,删除所有空白行,然后在段落之间插入两个空白行(最后没有)比计算所有空白行并仅在有两个以上空白行时才删除要容易得多。除非您正在处理巨大的文件,否则我认为这两种方法之间不会有任何性能差异。这是一个使用 re
的快速但肮脏的解决方案:
import re
# Reads from file
f = open('test.txt', 'r+')
txt = f.read()
# Removes all blank lines
txt = re.sub(r'\n\s*\n', '\n', txt)
# Adds two blanks between all paragraphs
txt = re.sub(r'\n', '\n\n\n', txt)
# Removes the blank lines from the EOF
txt = re.sub(r'\n*\Z', '', txt)
# Writes to file and closes
f.write(txt)
f.close()
之前:
One line below
None below
Three below
EOF with one blank line below (stackoverflow's code thingy omits it)
之后:
One line below
None below
Three below
EOF with one blank line below
关于Python脚本删除段落之间和文件末尾的多个空白行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22902946/