我试图创建一个程序,读取文件中的行,并计算每行的总和,然后打印出来。它应该跳过仅为注释且为空的行,但在计算行数时仍然计算它们。程序还应该能够从文件中创建变量并使用它们。我目前编写了以下代码:
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
示例文件中的空格和奇怪的格式是故意的。当前,所有行都作为无效语句返回。任何帮助都将不胜感激。你知道吗
这个程序很难修复,有很多错误(在我看来,实际上很难找到正确的东西)。作为一个示例,请考虑文件的fery第一个非注释行:
代码将无法解析:
num_list1
将是:而且没有一个
if
案例对第一项有效,其中token
将是"x123"
。你知道吗token in "abcdefghijklmnopqrstuvwxyz"
为假token == '+'
为假token == '-'
为假token == ''
为假所以我们到了
raise BadStatement
相关问题 更多 >
编程相关推荐