我正在尝试创建一个程序,该程序读取文件的各行,并取每一行的总和并进行打印。它应该跳过仅是注释且为空的行,但在对行进行计数时仍要对其进行计数。该程序还应该能够从文件中创建变量并使用它们。我目前编写了以下代码:
import sys
class BadStatement(Exception):
#creates an exeption called BadStatement to be used in exception handling
pass
def interpret_statements(filename):
#opens a file, checks if it is a valid file, and runs the program
try:
with open(filename) as f:
lines = f.readlines()
except FileNotFoundError:
print('specify filename')
loop_lines(lines)
def loop_lines(lines):
#goes through each line in the file prints the sums
line_num=1
line_sum=0
for line in lines:
line_sum=process_line(line)
line_num=line_num+1
if line_sum == None:
print("Line %i: Invalid Statement" %(line_num))
elif line_sum==0:
continue
else:
print("Line %i: %s" %(line_num, line_sum))
def process_line(line):
#takes each line in the file and preforms the calculations in order to get the value of each line
num_list=line.split()
variable_dict = {}
add = True
line_sum = 0
try:
for token in num_list:
if token in "abcdefghijklmnopqrstuvwxyz":
check_variable(variable_dict, token)
elif token == '+':
add = True
elif token == '-':
add = False
elif token == '':
continue
else:
raise BadStatement
try:
if add == True:
line_sum += float(token)
elif add== False:
line_sum -= float(token)
except ValueError:
raise BadStatement
return line_sum
except BadStatement:
return None
def check_variable(variable_dict, line):
#checks to make sure all noninteger values are defined
num_list1 = line.split()
sum=0
for each in num_list1:
if num_list1[0] == "=":
sum=num_list1[2]
if num_list1[each.index-1] == '+':
sum += float(each)
elif num_list1[each.index-1] =='-':
sum -=float(each)
return sum
variable_dict[num_list1[0]] = sum
return variable_dict
def check_for_valid_number(line):
number_valid = False
while number_valid == False:
try:
process_line(line)
number_valid = True
except ValueError:
pass
文件示例如下:
# Test correct expression statements
14.4
23.4 + -19 + 98223
10 - 34 + 12.66 - 28 - 3323.2 + 12
14.3
92 - 13 # here is a comment after an expression
34 + 13#and another comment
# Test correct assignment statements
x123 = 19278
salary = 873 - 13
time = -123.33 + salary - 123 + 23 + 0 + -123 - x123
x123 = x123 + 15 # reassign the value of x123
# And expression statements with variables
x123
14.4 - salary
time + salary - 10 + x123
# Now test some invalid statements
1474 +
820.34 - junk # junk has not been defined
2884 - -1293 + 399 t 266
23.8 - 203.3 +
+ 123.2 - 23.2
2884.2 + 293 - 23.2 283.3 + +
34.8 273 - 12
x =
x = salary + time = 15
x$y34 = 17
19 = 19
1xyz = 123
示例文件中的空格和古怪的格式是有意的。当前,所有行都作为无效语句返回。任何帮助将不胜感激。
答案 0 :(得分:0)
该程序很难修复,有很多错误(实际上,我认为很难找到正确的方法)。举个例子,考虑文件的第一行非注释行:
x123 = 19278
该代码将无法解析它:num_list1
将是:
["x123", "=", "19278"]
第if
个案例都不适用于第一个项目,其中token
为"x123"
。
token in "abcdefghijklmnopqrstuvwxyz"
是错误的token == '+'
是错误的token == '-'
是错误的token == ''
是错误的所以我们进入raise BadStatement