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

时间:2015-05-03 20:09:18

标签: python while-loop readline counting

我试图制作一个脚本:

  • 从文件
  • 逐行读取一行文本
  • 对于每一行,查看数组中是否有任何短语(animal_keywords)
  • 如果有,请将动物数量增加1
  • 如果没有,请将其他计数增加1
  • 在最后打印计数

我的输入文件是list.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

2 个答案:

答案 0 :(得分:0)

行:

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'中的代码后文件自动关闭,所以 这是一种很好的做法。

答案 1 :(得分:0)

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

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