我有一个名为dogs.txt的文本文件,其中包含以下行。
'#'彩色身体毛发类型
白色大硬保守
黄色大硬保守
棕色大软暴力 黄色大软保守 棕色小坚硬保守 棕色小坚硬保守白小坚硬保守
黄色小软暴力黄小硬暴力
棕色大硬保守白色大软保守
黄色小软暴力 棕色小软保守棕色大暴力
棕色小坚硬保守黄小硬暴力
每条线代表一只狗。当人输入dogs.txt。
时,我希望输出显示两件事那里有多少条狗?检查
有多少只狗是黄色和暴力的?
输出会告诉你有16只狗。
我接下来需要做的是发现这16只狗中有多少是黄色和暴力的。我一直坚持如何做到这一点。我想我将不得不使用infile.read(),但我不确定如何。请帮帮我们。
答案 0 :(得分: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
答案 1 :(得分: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)
答案 2 :(得分: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)
答案 3 :(得分: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)