首页 > 解决方案 > Python:计算有多少行有特定的单词

问题描述

我目前正在编写一个脚本,该脚本在文件中逐行计算两个特定单词。但是在运行我的脚本时,即使这两个单词都存在于行中,结束计数也每次为零。

这是我的代码:

file = open('sample.txt','r')

word1 = 'cookies'
word2 = 'waffles'
combined = word1 and word2

count = 0
for line in file.read():
    if combined in line:
        count = count+1
print(count)

文件内容:

I love cookies and waffles
I love cookies and waffles

我期望的输出是: 2

实际输出是什么: 0

如果有人可以向我解释如何让我的脚本正常运行,我会非常高兴:)

提前感谢您的每一个帮助和建议:)

标签: python-3.x

解决方案


这就是你可以做到这一点的方法。如果您希望该行中的两个词使用all而不是any.

words = ["cookies", "waffles"]
count=0
for line in file.read():
    if any(word in line for word in words):
        count+=1 
print(count)

推荐阅读