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

2024-06-30 16:57:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个剧本:

  • 从文件中逐行读入文本
  • 对于每一行,查看是否有数组中的短语(关键字)
  • 如果有,增加动物数量1
  • 如果没有,则将其他计数增加1
  • 最后打印计数

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

Tags: notreecountlinepandamediadocuments计数
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

相关问题 更多 >