【发布时间】:2016-02-14 22:57:03
【问题描述】:
我正在开发一个 Python 产品,它从文本文件中读取数据并将数字相加并在屏幕上显示结果。这是我的代码。它可以工作,但我想稍微修改一下输出。另外,有没有办法可以修改代码来解释一个非常新的程序(我的兄弟在 10 年级,他将开始 Python 作为他的第一个编程语言)。请注意,它不是 CSV 文件,不应该这样使用。它是一个文本文件,其内容用逗号分隔。
import sys
readFile = open("Products.txt", "r")
#reportfile = open("report.txt", "w")
reportfile = sys.stdout
Categories_seen = []
Current_category = None
Category_sum = 0
Total_sum = 0
line = readFile.readline()
for line in readFile:
category,product,sales2014,sales2015 = line.strip().split(',')
sales2015 = int(sales2015)
if category not in Categories_seen:
if Current_category is not None: # Subroutine, if possible
print( Current_category,
Category_sum, file=reportfile)
Current_category = category
Category_sum = sales2015
Total_sum += sales2015
Categories_seen.append(Current_category)
elif Current_category == category:
Category_sum += sales2015
Total_sum += sales2015
if Current_category is not None: # Subroutine, if possible
print("Total sales for", Current_category, "in 2015:",
Category_sum, file=reportfile)
print("----------", file=reportfile)
print("Total sales for the farmer in 2015:", Total_sum, file=reportfile)
现在的输出是这样的
Vegetables 25691
Fruits 11796
Total sales for Condiments in 2015: 17649
----------
Total sales for the farmer in 2015: 55136
But I would like the out to be like
Products : Sales
Vegetables : 25691
Fruits : 11796
Total sales for Condiments in 2015: 17649
----------
Total sales for the farmer in 2015: 55136
它读取的文本文件看起来像
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
【问题讨论】:
-
"一个文本文件,其内容用逗号分隔"。您刚刚描述了一个 CSV 文件(逗号分隔变量)。
-
我们应该在代码中使用 CSV
-
@Ian 逗号分隔的值
-
@KlausD。正确的。我知道当我输入某些内容时感觉不对,但我懒得在谷歌上搜索确切的措辞。
-
@JakeMeyer 我们无法帮助您,因为我们不知道您想如何修改输出。如果您需要有关代码的一般建议,请考虑使用 codereview.stackexchange.com 而不是 Stack Overflow。
标签: python parsing python-3.x split strip