我编写了一个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')
答案 0 :(得分:1)
这里有一些未经测试的代码:
import re
new_lines = re.compile('\n{2,9}')
with open(FILE) as f:
contents = f.read()
contents = re.sub(new_lines, '\n\n\n', contents.strip())
with open(FILE, 'w') as f:
f.write(contents)
首先删除末尾的空白行。然后,正则表达式匹配文件内容中2到9个换行符的实例,并用re.sub()
函数替换这3个换行符。
答案 1 :(得分:1)
实际上更容易删除所有空白行,然后在段落之间插入两个空白行(最后没有空白行),而不是计算所有空白行,只有在两行以上时才删除。除非你处理大文件,否则我认为两种方法之间的性能差异不大。这是使用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
答案 2 :(得分:0)
我知道所要求的答案是python,但我相信这可能是一种过度杀伤。
为什么不直接在shell上预处理文件?使用grep
或sed
或awk
来完成此操作。
这是grep版本:
$ grep -v '^$' input.txt > output.txt
答案 3 :(得分:0)
到目前为止,这个问题尚未真正得到回答。 这是一个可行的解决方案,但我认为可能会更好。
newtext = ''
counter = 0
for line in text.splitlines():
line = line.strip()
if len(line)==0:
counter += 1
if counter<=2:
newtext += line + '\n'
else:
newtext += line + '\n'
counter = 0