簡體   English   中英

用包含某些字符串的行中的單個空格替換雙倍空格

[英]Replacing double space with single space in line containing certain string

我有一個帶有行和列的大文本文件。 在文件中的所有字符串/數據之間,有一個雙倍空格。 但是,為了使我的特定代碼正常工作,我需要將雙精度空格僅在某些行中變為單個空格。 這些行都以相同的字符串開頭。

我試過了:

with open(outfile) as f3, open(outfile2,'w') as f4:
    for line in f3:
         line = line.strip()
         if "SAMPLE" in line:
             " ".join(line.split())
         if 'xyz' not in line and len(line) >=46:
             f4.write(line+'\n')  

我嘗試過:

import re
with open(outfile) as f3, open(outfile2,'w') as f4:
    for line in f3:
         if "SAMPLE" in line:
             re.sub("\s\s+" , " ", line)
         if 'xyz' not in line and len(line) >=46:
             f4.write(line)  

都不起作用。 第二個if語句刪除了我不想刪除的某些行,這樣就不會消失(這按預期工作)。 但是,文本文件中所有數據之間仍保留雙倍間距。 如何在包含“ SAMPLE”的文件中的行替換單個間距的行中單詞之間的雙倍空格的地方?

您的問題是字符串的可變性, " ".join(line.split())創建一個新字符串,這很可能是您所需要的,但您應將其分配回line變量。

if "SAMPLE" in line:
    line = " ".join(line.split())

以后編輯:
第二個if有點“奇怪”……預期的結果是什么?

if not line or (':' and len(line) >=46):
    f4.write(line) 

尤其是第二部分... ':'始終為True ,似乎沒用,可能是拼寫錯誤或缺少某些內容。 僅當該line空或無(評估為False )或該行的長度>= 46時,才將其寫入文件。

該代碼應如下所示:

with open(outfile) as f3, open(outfile2,'w') as f4:
    for line in f3:
         line = line.strip()
         if "SAMPLE" in line:
             # we clean eventual double/multi-space if the line contains "SAMPLE"
             line = " ".join(line.split()) 
         if 'xyz' not in line and len(line) >=46:
             # write to the second file only the lines that
             # don't contain 'xyz' and have the length of the line => 46 
             f4.write(line+'\n')  

嘗試這個:

s = " ".join(your_string.split())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM