2017-04-08 58 views
2

我想要字符串中包含兩個子字符串 .txt文件中的行數。如何從文本文件中計算字符串中字符串的發生次數 - python

我試過如下:

with open(filename, 'r') as file: 
    for line in file: 
     wordsList = line.split() 
     if any("leads" and "show" in s for s in wordsList): 
      repetitions +=1 

print "Repetitions: %i" % (repetitions) 

但它似乎並不奏效,因爲它應該。 隨着下面的演示輸入文件我3次重複當它應該是2:

www.google.es/leads/hello/show 
www.google.es/world 
www.google.com/leads/nyc/oops 
www.google.es/leads/la/show 
www.google.es/leads/nope/pop 
leads. 
show 

我也試過chaning「任何」爲「所有」,但我得到更奇怪的結果。

+4

你的意思是'「線索」,在S和「秀」在s' –

+0

@ThierryLathuille哦,上帝,它的工作謝謝! – ignasibm

回答

0

"leads" and "show" in s被解釋爲: "leads" and ("show" in s)因爲有優先權。

Python試圖將「引線」解釋爲布爾值。由於它是一個非空字符串,它的計算結果爲True。

所以,你的表情是相當於"show" in s

你是什麼意思是: "leads" in s and "show" in s

相關問題