我想写一个剧本:
我的输入文件是列表.txt(计数应为动物:9和其他:3)你知道吗
C\Documents\Panda\Egg1
D\Media\Elephant\No
F\Pictures\tree
H\Lemur\12
C\Documents\Panda\Egg1
D\Media\Elephant\No
F\Pictures\tree
H\Lemur\12
C\Documents\Panda\Egg1
D\Media\Elephant\No
F\Pictures\tree
H\Lemur\12
我的剧本是:
## Import packages
from time import sleep
import os
## Set up counts
animal_count = 0
other_count = 0
## List of known keywords (Animals)
animal_keywords = ['Panda', 'Elephant', 'Lemur']
## Open file, read only
f = open('list.txt')
## Read first line
line = f.readline()
##If file not empty, read lines one at a time until empty
while line:
print line
line = f.readline()
if any(x in f for x in animal_keywords):
animal_count = animal_count +1
##If it doesn't, increase the other count
else:
other_count = other_count + 1
f.close()
print 'Animals found:', animal_count, '|||| ' 'Others found:', other_count
脚本没有正确读取行或正确计数。我一直在兜圈子!你知道吗
我当前得到的输出是:
C\Documents\Panda\Egg1
D\Media\Elephant\No
Animals found: 0 |||| Others found: 2
线路:
对于while循环的每次迭代都是
True
。 所以,最有可能的情况是,animal_count
的值是+1 文件里的每一行,不管有没有动物你想要的东西更像:
执行“with block”中的代码后,文件将自动关闭,因此 这是个好习惯。你知道吗
您应该遍历文件对象,检查每行中是否有任何动物关键字:
相关问题 更多 >
编程相关推荐