我想计算一个字符串包含两个子字符串的.txt文件上的行数。
我尝试了以下方法:
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
我也尝试将“ any”换为“ all”,但得到的结果甚至更陌生。
"leads" and "show" in s
被解释为:"leads" and ("show" in s)
由于优先级。
Python尝试将“线索”解释为布尔值。由于它是一个非空字符串,因此其值为True。
所以,你的表情相当于 "show" in s
您的意思是: "leads" in s and "show" in s
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句