2017-04-08 60 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

相关问题