-2

我有一个名为 dogs.txt 的文本文件,其中包含以下几行。

'#'颜色体毛类型

白大硬保守

黄色大硬保守

棕色大号软暴力

黄色大号软保守

棕色小硬保守

棕色小硬保守

白色小硬保守

黄色小软暴力

黄色小硬暴力

棕色大硬保守

白色大软保守

黄色小软暴力

棕色小软保守

棕色大硬暴力

棕色小硬保守

黄色小硬暴力

每条线代表一只狗。当人员输入 dogs.txt 时,我希望输出显示两件事。

  1. 有多少只狗?查看

  2. 有多少狗是黄色和暴力的?

输出会告诉你有 16 条狗。

接下来我需要做的是找出这 16 条狗中有多少是黄色和暴力的。我一直坚持如何做到这一点。我想我将不得不使用 infile.read() 但我不确定如何。请帮助各位。

4

4 回答 4

2

这是检查黄色和暴力号码的快速方法:

with open('dogs.txt') as f:
    f.readline() # Skip first line
    print sum({'yellow','violent'}.issubset(line.split()) for line in f)

但是,当我添加行号检查时,它并不那么优雅

with open('dogs.txt') as f:
    f.readline() # Skip first line
    i, num_dogs = 0, 0
    for line in f:
        num_dogs += {'yellow','violent'}.issubset(line.split())
        i += 1
    print i, num_dogs
于 2013-03-20T01:05:38.140 回答
1
yellow_and_violent = 0    
for line in infile:
    if line.strip() and line[0]!='#':               
        lines+=1
    if ('yellow' in line) and ('violent' in line'):
        yellow_and_violent += 1

还有几件事:

  • 如果找不到文件,而不是将变量设置为不分析文件,您可以引发自定义异常
  • 你不应该使用类名作为变量名(例如file

这使:

import os.path

filename = input("Enter name of input file >")
try:
    infile = open(filename, "r")
except IOError:
    raise Exception("Error opening file '%s', analysis will not continue" % filename)

dogs = 0
yellow_and_violent = 0

for line in infile:
    if line.strip() and line[0]!='#':               
        dogs += 1
    if ('yellow' in line) and ('violent' in line):
       yellow_and_violent += 1
print("Total dogs =",dogs)
print("Yellow and violent dogs = ", yellow_and_violent)
于 2013-03-20T00:23:24.290 回答
1

使用正则表达式:

import os.path
import sys 
import re
reg = re.compile("^yellow.*violent")
try:
    file=sys.argv[1]
    infile=open(file,"r")
except IOError:
      raise Exception("open '%s' failed" % filename)
lines=0
yv=0
for line in infile:
  if line.strip() and line[0]!='#':
    lines+=1
    if reg.match(line):
      yv+=1
print("Total dogs =",lines)
print("Total yv dogs =",yv)
于 2013-03-20T00:25:52.297 回答
0
dog_counter = 0
yellow_and_violent = 0
with open('dog.txt', 'r') as fd:
    for line in fd.readlines():
        if line.startswith("'#'") or (not line.strip()):
            continue
        dog_counter += 1
        if ('yellow' in line) and ('violent' in line):
            yellow_and_violent += 1
print("Total dogs: %d" % dog_counter)
print("yellow and violent dogs: %d" % yellow_and_violent)
于 2013-03-20T03:58:20.413 回答