[英]PYTHON Basic Text Browser/Scraper. How to remove blank lines but keep at least one between paragraphs
[英]Python script to remove multiple blank lines between paragraphs and end of file
我編寫了一個 python 腳本來捕獲我想要的數據,但我有一個包含多個段落的結果文本文件,但每個段落由不同的空行分隔 - 從 2 到 8。
我的文件在文件末尾也有多個空行。
我希望 Python 在段落之間留下不超過 2 個空行,並且文本文件末尾沒有空行。
我已經嘗試過循環和 line.strip、replace 等,但我顯然不知道如何將它們放在一起。
到目前為止我一直在使用的例子
wf = open(FILE,"w+")
for line in wf:
newline = line.strip('^\r\n')
wf.write(newline)
wf.write('\n')
這是一些未經測試的代碼:
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 個換行符替換它們。
實際上,刪除所有空行然后在段落之間插入兩個空行(最后沒有)比計算所有空行並僅在有兩個以上時才刪除更容易。 除非您正在處理大文件,否則我認為這兩種方法之間不會有任何性能差異。 這是使用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
到目前為止,這個問題還沒有得到真正的回答。 這是一個有效的解決方案,但我認為它可能會更好。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.