比较和计数 python 中的项目(while 循环)

comparing and counting items in python (while loop)

我正在尝试制作一个脚本:

我的输入文件是list.txt(计数应该是animals:9和other:3)

C\Documents\Panda\Egg1
D\Media\Elephant\No
F\Pictures\tree
H\Lemur
C\Documents\Panda\Egg1
D\Media\Elephant\No
F\Pictures\tree
H\Lemur
C\Documents\Panda\Egg1
D\Media\Elephant\No
F\Pictures\tree
H\Lemur

我的脚本是:

## 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

行:

if any(x in f for x in animal_keywords):
        animal_count = animal_count +1
对于 while 循环的每次迭代,

将是 True。 所以,很可能你得到了 animal_count 的 +1 文件中的每一行,无论是否有动物

你想要更像的东西:

with open('list.txt') as f:
    for line in f:
        if any(a in line for a in animal_keywords):
            animal_count += 1
        else:
            other_count += 1

执行'with block'中的代码后文件自动关闭,所以 这是个好习惯。

您应该遍历文件对象,检查每一行中是否有任何动物关键字:

animal_count = 0
other_count = 0

## List of known keywords (Animals)
animal_keywords = ['Panda', 'Elephant', 'Lemur']

# with will automatically close your file
with open("list.txt") as f:
    # iterate over the file object, getting each line
    for line in f:
        # if any keyword is in the line, increase animal count
        if any(animal in line for animal in animal_keywords):
            animal_count += 1
        # else there was no keyword in the line so increase other
        else:
            other_count += 1