擅长:python、mysql、java
<p>问题是你在做什么</p>
<pre><code>for line in f:
if "world" in line:
x=x+1
</code></pre>
<p>解决这个问题的一种方法是把“世界”的每一个实例都数一行。你知道吗</p>
<pre><code>for line in f:
if "world" in line:
x+=line.count("world")
</code></pre>
<p>另一种方法是计算每个单词。你知道吗</p>
<pre><code>for line in f:
for word in line.split():
if word == "world":
x+=1
</code></pre>
<p>下次请记住:
1对于f中的行:将它作为一整行而不是一个单词,如果该行中有一个单词的多个实例,那么代码只计算有多少行包含该单词。
2您可能喜欢的一个提示是x=x+1表示x等于x加1的值。如果我是你,我会看看这个
<a href="https://www.tutorialspoint.com/python/python_basic_operators.htm" rel="nofollow noreferrer">https://www.tutorialspoint.com/python/python_basic_operators.htm</a>
它教你如何使用基本运算符,这可以节省很多时间和挫折。在您的示例中,x+=1与x=x+1相同。你知道吗</p>
<p>祝你好运!你知道吗</p>