2017-04-08 5 views
2

は.txtファイルの行数をカウントします。文字列には2つのサブストリングが含まれています。文字列中の文字列内のサブストリングを数える方法 - 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) 

をしかし、それはそれが必要として動作していないようです。それは2であるべきときに私は3回繰り返しを得た次のデモ入力ファイルを使用して :

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' –

+0

@ThierryLathuilleでs内の '「リード」と「ショー」を意味し、それが働いた神ああありがとうございました! – ignasibm

答えて

0

"leads" and "show" in sは、次のように解釈されます。 "leads" and ("show" in s)

Pythonは "leads"をブール値として解釈しようとします。空でない文字列であるため、Trueと評価されます。

だから、あなたの表現は、あなたが何を意味するか"show" in s

と同等です: "leads" in s and "show" in s

関連する問題