![](/img/trans.png)
[英]Most computationally efficient way to remove last word from string if it's less than x number of characters?
[英]Python - Remove line with less than "x" number of characters while preserving blank lines
我正在打開一個包含列和行的文本文件。 有些行的字符數比其他行多,我正在嘗試刪除只有 <# 個字符的行。
該文件還包含一些我需要保留在文件中的空白間隔行。
with open(outfile) as f, open(outfile2,'w') as f2:
for x in f:
if (':') not in x and (',') not in x:
newline=x.strip()+'\n'
if len(newline.rstrip()) >= 43:
f2.write(newline)
第一個if-statement
刪除了文件中我不想要的一些文本行,同時還添加了我需要的那些額外的間隔行。 第二個if-statement
試圖刪除具有 <# 個字符的數據行,但此命令也刪除了我需要保留的那些空白間隔行。 如何在保留間隔行的同時擺脫那些包含 <# 個字符的行?
使用以下綜合方法:
with open(outfile) as f, open(outfile2, 'w') as f2:
for line in f:
line = line.strip()
if not line or (':' not in line and ',' not in line and len(line) >= 43):
f2.write(line + '\n')
關鍵的if
語句允許寫入空行或滿足所需條件的行。
with open(outfile) as f, open(outfile2,'w') as f2:
for x in f:
if not x.strip().replace("\n",""):
f2.write(x)
continue
elif (':') not in x and (',') not in x:
newline=x.strip()+'\n'
if len(newline.rstrip()) >= 43:
f2.write(newline)
我想這個額外的 if 語句會解決你的問題。 如果沒有,您可以創建一個條件語句的變體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.