2024-03-28 17:07:08 发布
网友
我有这个文本文件:
hello worldworld hello world
hello world
world hello world
这是我的密码:
f = open("dummy.txt","r+") x = 0 for line in f: if "world" in line: x = x + 1 print x f.close()
但它打印的是2,而不是3。你知道吗
2
3
问题是你在做什么
for line in f: if "world" in line: x=x+1
解决这个问题的一种方法是把“世界”的每一个实例都数一行。你知道吗
for line in f: if "world" in line: x+=line.count("world")
另一种方法是计算每个单词。你知道吗
for line in f: for word in line.split(): if word == "world": x+=1
下次请记住: 1对于f中的行:将它作为一整行而不是一个单词,如果该行中有一个单词的多个实例,那么代码只计算有多少行包含该单词。 2您可能喜欢的一个提示是x=x+1表示x等于x加1的值。如果我是你,我会看看这个 https://www.tutorialspoint.com/python/python_basic_operators.htm 它教你如何使用基本运算符,这可以节省很多时间和挫折。在您的示例中,x+=1与x=x+1相同。你知道吗
祝你好运!你知道吗
if "world" in line: x = x + 1
如果行中至少有一个引用,则添加1。但一行中有两个实例,因此计数失败。你知道吗
只要做:
x += line.count("world")
一行使用sum和理解:
sum
sum(line.count("world") for line in f)
请注意,不尊重单词边界。子字符串也匹配。考虑改用line.split().count("world"),即使它不能正确地分割标点符号。look here正确分割标点符号。你知道吗
line.split().count("world")
F = open("Dummy.txt", "r+") string = F.read() # For storing the file as a string print string.count("world") # Print the count of "world" in the file F.close()
问题是你在做什么
解决这个问题的一种方法是把“世界”的每一个实例都数一行。你知道吗
另一种方法是计算每个单词。你知道吗
下次请记住: 1对于f中的行:将它作为一整行而不是一个单词,如果该行中有一个单词的多个实例,那么代码只计算有多少行包含该单词。 2您可能喜欢的一个提示是x=x+1表示x等于x加1的值。如果我是你,我会看看这个 https://www.tutorialspoint.com/python/python_basic_operators.htm 它教你如何使用基本运算符,这可以节省很多时间和挫折。在您的示例中,x+=1与x=x+1相同。你知道吗
祝你好运!你知道吗
如果行中至少有一个引用,则添加1。但一行中有两个实例,因此计数失败。你知道吗
只要做:
一行使用
sum
和理解:请注意,不尊重单词边界。子字符串也匹配。考虑改用
line.split().count("world")
,即使它不能正确地分割标点符号。look here正确分割标点符号。你知道吗相关问题 更多 >
编程相关推荐