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)