2013-03-23 21 views
1

我的問題是類似this one,但我想搜索多個chars的發生,例如gde,然後打印線所有指定的字符都存在。使用Python來搜索文本文件中的特定字符的發生

我曾嘗試以下,但它沒有工作:

searchfile = open("myFile.txt", "r") 
for line in searchfile: 
    if ('g' and 'd') in line: print line, 
searchfile.close() 

我得到了它的「G」或「d」或兩者在其中,我要的只是兩個OCCURENCES線,至少不是其中之一,因爲運行上述代碼的結果。

+3

你有嘗試過什麼嗎?這不難實現,不需要正則表達式。 – Blender 2013-03-23 22:00:20

回答

2

這條線:

if ('g' and 'd') in line: 

相同

if 'd' in line: 

因爲

>>> 'g' and 'd' 
'd' 

你想

if 'g' in line and 'd' in line: 

,或者更好:

if all(char in line for char in 'gde'): 

(你可以使用交集太多,但這是不太普及。)

+0

謝謝!這工作非常完美。 – engineervix 2013-03-23 22:42:32

0

當涉及到模式匹配時,正則表達式肯定會對您有所幫助,但似乎您的搜索比這更容易。請嘗試以下操作:

# in_data, an array of all lines to be queried (i.e. reading a file) 
in_data = [line1, line2, line3, line4] 

# search each line, and return the lines which contain all your search terms 
for line in in_data: 
    if ('g' in line) and ('d' in line) and ('e' in line): 
     print(line) 

這個簡單的東西應該可以工作。我在這裏做一些假設: 1.搜索條件的順序無關緊要 2.大小寫不處理 3.不考慮搜索條件的頻率。

希望它有幫助。

+0

oops,只需閱讀上面的示例代碼 - 並將其運行在具有預期輸出的測試文件中,即只返回包含BOTH條款的行。並認識到,我的示例,如果真的與你的相同:) – 2013-03-23 22:19:50

+1

g'和'd'和'e'in line'將不起作用 - 這相當於''e'in line';像'g'和'e'這樣的非空字符串是真實的。例如,'line ='fred';打印'g'和'd'和'e'in line'打印爲真。 – DSM 2013-03-23 22:30:48

+0

謝謝,好點。修訂解答 – 2013-03-24 09:14:40

4
if set('gd').issubset(line) 

這有過兩次不打算通過了的c in line迭代每個檢查的優勢整行

相關問題