2015-11-06 61 views
1

我想在讀取文件時丟棄標題行。標題行從一組有限的字符串開始,但我不能僅僅檢查子字符串,因爲有效的內容行可能會在字符串的稍後包含關鍵字。檢查字符串是否以Python中的幾個子字符串之一開始

我無法弄清楚如何爲一組子字符串執行line.startswith(「substring」),這是我的第一次嘗試。我的意思是,我可以把它放在一個單獨的部分,並根據它設置一個變量,但這是很糟糕的。我只是想運行邏輯測試並作出相應的響應。

我已經嘗試了以下幾個變體,因爲我有已知的4個字符的開始子字符串的豪華,但我敢肯定,我的語法錯誤,錯誤,錯誤。它解析,但不拒絕任何行。

cleanLines = [] 
line = "sample input here" 
if not line[0:3] in ["node", "path", "Path"]: #skip standard headers 
    cleanLines.append(line) 
+2

字符串切片中的結束索引是獨佔的。你只需要'line [0:4]'或簡單的'line [:4]' – inspectorG4dget

+0

Annnnd這就是所需要的。固定。如果你把這個作爲答案,我會立即選擇它。 – Bibliotango

+0

如果你知道如何使用長度不敏感的startswith(),我會非常感激。我討厭易碎的黑客。 – Bibliotango

回答

2

你的問題的事實,串切片獨家停止指數的莖:

In [7]: line = '' 

In [8]: line[0:3] 
Out[8]: '012' 

In [9]: line[0:4] 
Out[9]: '0123' 

In [10]: line[:3] 
Out[10]: '012' 

In [11]: line[:4] 
Out[11]: '0123' 

切片ij返回字符串開始i,在結束之間的字符串(但不包括)j

只是爲了讓你的代碼運行速度更快,你可能想在測試集的隸屬,而不是在名單:

cleanLines = [] 
line = "sample input here" 
blacklist = set(["node", "path", "Path"]) 
if line[:4] not in blacklist: #skip standard headers 
    cleanLines.append(line) 

現在,你實際上與該代碼做是startswith,這是不受任何長度參數限制:

In [12]: line = '' 

In [13]: line.startswith('0') 
Out[13]: True 

In [14]: line.startswith('0123') 
Out[14]: True 

In [15]: line.startswith('03') 
Out[15]: False 

所以,你可以這樣做是爲了排除標題:

cleanLines = [] 
line = "sample input here" 
headers = ["node", "path", "Path"] 
if not any(line.startswith(header) for header in headers) : #skip standard headers 
    cleanLines.append(line) 
+2

也可以使用'any(map(line.startswith,headers))'我覺得很酷。 –

相關問題