python-3.x - 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
如果有人可以向我解释如何让我的脚本正常运行,我会非常高兴:)
提前感谢您的每一个帮助和建议:)
解决方案
这就是你可以做到这一点的方法。如果您希望该行中的两个词使用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)
推荐阅读
- php - 有没有办法按照一定的标准将最多 3 个多维数组与 OOP PHP 对象组合成一个数组?
- curl - Linuxbrew curl证书问题
- r - R Highcharter - 共享工具提示(和各种工具提示参数)不起作用
- json - 使用正则表达式解析 Git Json
- javascript - 寻找合适的代码架构来嵌入音频,同时防止页面更新闪烁(HTML/javascript/Ajax)
- css - 网格列表向左浮动
- c# - 通过引用传递 DataGridViewCell
- gcc - 为什么我的内联汇编代码会导致三重错误?
- r - 在 tsCV 中循环预测函数
- python - 在 Python 函数调用中创建生成器 - 为什么会这样?