簡體   English   中英

在Python中使用strip刪除“ \\ n”?

[英]Remove “\n” with strip in Python?

我正在處理文件文本,但是由於它的開頭也有空格,當我嘗試使用strip模式和list理解來刪除\\n ,我得到了一個包含空元素的列表(" ")而我沒有不知道如何刪除它們。 我有一個文本,我的代碼是:

with open(filename) as f:
    testo= f.readlines()
[e.strip() for e in testo]

但我得到這樣的清單:

[' ', ' ', 'word1', 'word2', 'word3', ' ']

我想知道是否可以使用strip方法解決該問題,否則可以使用另一種方法解決該問題。

您正在獲取那些空字符串,因為很少有幾行只是空換行符。 這是清除這些空字符串的代碼。

with open(filename) as f:
    testo = [e.strip() for e in f.readlines()]
    final_list = list(filter(lambda x: x != '', testo))
    print(final_list)

沒有lambda並使用map:

with open(filename) as f:
    final_list = list(filter(bool, map(str.strip, f)))
    print(final_list)

另一個解決方案是:

with open(filename) as f:
 testo =  [x for x in f.read().splitlines() if x]
 print(testo)

對於第二個解決方案,來源是: https//stackoverflow.com/a/15233379/2988776

有關性能升級,請參閱@Patrick的答案

您可以使用生成器來讀取所有行,並用strip()不需要的換行符。

在生成器中,您僅使用那些“ Truthy”元素-空字符串被視為False

優點:您僅創建一個列表,並刪除了空字符串:

寫文件:

filename = "t.txt"
with open(filename,"w") as f:
    f.write("""

  c
  oo
  l

  te
  xt
  """)

處理文件:

with open(filename) as f:
    testo = [x for x in (line.strip() for line in f) if x] # f.readlines() not needed. f is
                                                          # an iterable in its own right

print(testo)  # ['c', 'oo', 'l', 'te', 'xt']

您可以執行類似的操作:

testo = [line.strip() for line in f if line.strip()]

但這將執行strip()兩次,效率會略低。

輸出:

['c', 'oo', 'l', 'te', 'xt']

Doku:


Eli Korvigo建議的替代方法是:

testo = list(filter(bool, map(str.strip, f)))

與本質上是相同的-使用生成器comp替換顯式列表comp到f mapstr.strip f (生成生成器),並對其應用filter以將其饋送到列表中。

有關filter,map,bool的文檔,請參見內置函數

我更喜歡我; o)

根據您顯示給我們的數據,看起來好像有一條線,其中只有一個空格。 考慮到這一點,您必須決定是否要這樣做。

如果您需要它,那么您的代碼應如下所示:

with open(filename) as f:
   testo=f.readlines()
list(filter(None, (l.rstrip('\n') for l in testo)))

如果您不希望僅使用空格字符的行,則可以執行以下操作:

with open(filename) as f:
   testo=f.readlines()
[e.rstrip('\n') for e in testo if e.strip()]

在這種情況下,我們避免將“帶有前導和尾隨空格的單詞”剝離為“帶有前導和尾隨空格的單詞”,因為在某些情況下,它可能會更改行的語義:)

暫無
暫無

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

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