您好我是一名非常新的程序员,他自学Python。我遇到了一个非常有趣的问题,需要一些帮助来为它创建一个程序。它就像这样
酒店销售人员在文本文件中输入销售。每行包含以下内容,以分号分隔:客户的名称,销售的服务(如晚餐,会议,住宿等),销售金额以及该事件的日期。编写一个读取此类文件的程序,并显示每个服务类别的总金额。如果文件不存在或格式不正确,则显示错误。
提示要处理和发出的文件的名称 错误消息,如果无法打开该文件则终止
验证每一行的项目数是否正确 如果不是
验证美元金额是否为有效浮点数 数字,如果不是
保持列表中包含遇到的类别(他们 可能与下面不同)和另一个列表 每个类别的累计美元金额。这是两个 列表,但一个元素与中的元素相关 另一个(按位置)
处理完所有数据后关闭文件
显示每个类别和总数
我们的示例文本文件看起来像这样
Bob;Dinner;10.00;January 1, 2015
Tom;Dinner;14.00;January 2, 2015
Anne;Lodging;125.00;January 3, 2015
Jerry;Lodging;125.00;January 4, 2015
这是我想要做的。我试图了解这一点并得到Stack Overflow专家的帮助,以便在学习的同时解决这个问题。谢谢大家!
import sys
def main():
try:
line = infile.readline()
for line in infile:
inputFileName = input("Input file name: ")
infile = open(inputFileName, "r")
fields = line.split(";")
value = float(fields[1])
except:
print("Error: The file cannot be opened.")
sys.exit(1)
infile.close()
main()
答案 0 :(得分:1)
这是一个基本草图。这是未经测试的,因此可能包含拼写错误,逻辑错误等。此外,它不会检查您提到的所有错误情况。但是,它应该足以让你开始。主要技巧是throw an exception遇到错误,catch it可以处理错误。这会立即停止处理您想要的文件。另一个技巧是将dictionary映射类别保持为总计,这样您就可以按类别保持运行总计。
def main():
# Req 1.1: ask for a filename
file_name = input("Input file name: ")
try:
# To keep things simple we do all the file processing
# in a separate function. That lets us handle
# any error in the file processing with a single
# except block
amount_by_category = process_file(file_name)
# Req 6: display the categories - python will
# display the contents of a data structure when we print() it
print('Totals: ', amount_by_category)
except Exception, e:
# Reqs 1-3: display errors
print('Error processing file:', e)
def process_file(file_name):
# Req 1.2: open the file
infile = open(file_name, 'r')
# Req 4.1: somewhere to remember the categories
amount_by_catgeory = {}
# Reqs 2-4: we are dealing with a many line file
# Req 5: when we reach the end, python closes the file for us automatically
for line in infile:
# Req 2.1: each line should have 4 values separated by ;
fields = line.split(';')
# Req 2.2: does this line have 4 values?
if len(fields) != 4:
raise Exception('Expected 4 fields but found %s' % len(fields))
# Req 3: is the third value a number?
value = float(fields[2])
# Req 4.2: what category does this line belong to?
category = fields[1]
# Req 4.3.1: have we seen this category before?
if not category in amount_by_category:
# Req 4.3.2: accumulations start from 0?
amount_by_category[category] = 0.0f
# Req 4.4: increase the cumulative amount for the category
amount_by_category[category] += value
return amount_by_category