【发布时间】:2016-02-10 23:40:40
【问题描述】:
我正在尝试用 python 编写一个程序,我们必须在其中添加来自不同类别和子类别的数字。该计划是关于农民每年销售其农场的农产品的。我们必须从中读取的文本文件有 4 个类别。第一类是产品类型,例如蔬菜、水果、调味品。第二类告诉我们我们拥有的产品类型,例如土豆、苹果、辣酱。第三类告诉我们 2014 年的销售额,第四类告诉我们 2015 年的销售额。在这个程序中,我们只需要根据 2015 年的数字计算总数。 2014 年的数字存在于文本文件中,但不相关。
这是文本文件的样子
PRODUCT,CATEGORY,2014 Sales,2015 Sales
Vegetables,Potatoes,4455,5644
Vegetables,Tomatoes,5544,6547
Vegetables,Peas,987,1236
Vegetables,Carrots,7877,8766
Vegetables,Broccoli,5564,3498
Fruits,Apples,398,4233
Fruits,Grapes,1099,1234
Fruits,Pear,2342,3219
Fruits,Bananas,998,1235
Fruits,Peaches,1678,1875
Condiments,Peanut Butter,3500,3902
Condiments,Hot Sauce,1234,1560
Condiments,Jelly,346,544
Condiments,Spread,2334,5644
Condiments,Ketchup,3321,3655
Condiments,Olive Oil,3211,2344
我们要做的是将 2015 年的销售额(按产品)相加,然后是 2015 年所有产品的总销售额。
书面文本文件中的输出应如下所示:
2015 年蔬菜的总销售额:{在此处插入总数}
2015 年水果的总销售额:{在此处插入总数}
2015 年调味品的总销售额:{在此处插入总数}
2015 年农民的总销售额:{Insert total for all the 2015 年销售的产品}
除此之外,它还应该在 IDE 的 Python 运行屏幕上打印总计以及文本文件:
2015 年农民的总销售额:{Insert total for all the 2015 年销售的产品}
这是我的代码。它可以工作,但会在输出中打印出奇怪的第一行。另外,我宁愿不使用列表。还有其他方法吗?请不要使用 CSV,因为我们被指示将数据用作文本文件。
readFile = open("Products.txt", "r")
reportfile = open("report.txt", "w")
line = readFile.readline()
totalSum = 0
container = []
product = ()
sum=0
for line in readFile:
line=line.strip()
line=line.split(",")
if line[0] not in container:
print(product,sum, file=reportfile)
product = line[0]
totalSum += int(line[3])
sum = 0
sum += int(line[3])
container.append(product)
elif product == line[0]:
totalSum += int(line[3])
sum += int(line[3])
print(totalSum, file=reportfile)
【问题讨论】:
标签: python python-3.x split comma