Python 为食品加工公司读写文件

Python 为食品加工公司读写文件,python,parsing,python-3.x,Python,Parsing,Python 3.x,我正在从事一个Python项目,其中一家食品加工公司正试图计算今年的总销售额。Python必须从一个文本文件中读取数据,在该文件中,它被划分为多个类别,并由逗号分割。第一类是产品类型,可以是公司生产的谷物、巧克力糖等。第二类是所述产品的品牌,例如,用于谷物的Kaptain Krunch或用于巧克力的可可酱。第三类是上一财年(2014年)的销售额,最后一类是本财年(2015年)的销售额。请注意,仅计算2015财年的销售额。2014年在该计划中没有任何用处,但它确实存在。下面是文本文件的外观。它的名

我正在从事一个Python项目,其中一家食品加工公司正试图计算今年的总销售额。Python必须从一个文本文件中读取数据,在该文件中,它被划分为多个类别,并由逗号分割。第一类是产品类型,可以是公司生产的谷物、巧克力糖等。第二类是所述产品的品牌,例如,用于谷物的Kaptain Krunch或用于巧克力的可可酱。第三类是上一财年(2014年)的销售额,最后一类是本财年(2015年)的销售额。请注意,仅计算2015财年的销售额。2014年在该计划中没有任何用处,但它确实存在。下面是文本文件的外观。它的名字是product.txt

麦片粥,魔术球,22002344

麦片,卡普坦克伦克,33003123

麦片,可可邦戈,18002100

麦片粥,糖大口,43556500

谷物、燕麦和大麦、32995400

糖果,波普摇滚乐,546982

糖果,棒棒糖,12331544

糖糖,姜饼,2344221

糖果,Respur,12452211

巧克力,可可酱,33224300

巧克力,云雀,16002200

巧克力、强力牛奶、12342235

巧克力、杏仁浆果、9981233

调味品,花生酱,35003902

调味品,辣酱,12341560

调味品,果冻,346544

调味品,抹酱,23345644

我们希望做的是按产品添加2015财年的销售额,然后再添加2015年所有产品的总销售额

输出应该与写入的文本文件中的类似

2015年谷物总销售额:{在此处插入总数}

2015年糖果总销售额:{在此处插入总数}

2015年巧克力总销售额:{在此处插入总数}

2015年调味品总销售额:{在此处插入总数}


公司2015年的总销售额:{插入所有 2015年销售的产品}

除此之外,它还应该在IDE的Python运行屏幕上打印总计以及文本文件

公司2015年的总销售额:{插入所有 2015年销售的产品}

这是我的密码。我对Python和读写文件都是新手,所以我不能说我是否走上了正确的道路

PRODUCT_FILE = "products.txt"
REPORT_FILE = "report.txt"

def main():
    #open the file
    productFile = open(PRODUCT_FILE, "r")
    reportFile = open(REPORT_FILE, "w")

    # reading the file
    proData = extractDataRecord(productFile)
    product = proData[0]
    category = proData[1]
    salesLastYear = prodata[2]
    salesThisYear = proData[3]

    #computing
    product = 0.0
    product = salesThisYear


    productFile.close()
    reportFile.close()

def extractDataRecord(infile) :
   line = infile.readline()
   if line == "" :
      return []
   else :
      parts = line.rsplit(",", 1)
      parts[1] = int(parts[1]) 
      return parts

# Start the program.
main()

这里的简短说法是你做错了。如果可以的话,千万不要使用自己的解析代码。我建议看一看,并尝试使用它来“收缩”CSV解析,让您专注于其余的逻辑

使用
csv
简单重写并完成代码:

import collections
import csv

PRODUCT_FILE = "products.txt"
REPORT_FILE = "report.txt"

def main():
    # Easy way to get a dictionary where lookup defaults to 0
    categorycounts = collections.defaultdict(int)

    #open the files using with statements to ensure they're closed properly
    # without the need for an explicit call to close, even on exceptions
    with open(PRODUCT_FILE, newline='') as productfile,\
         open(REPORT_FILE, "w") as reportfile:
        pcsv = csv.reader(productfile)

        # Sum sales by product type letting csv parse
        # Filter removes empty rows for us; assume all other rows complete
        for category, brand, sales_lastyear, sales_thisyear in filter(None, pcsv):
            categorycounts[category] += int(sales_thisyear)

        # Print categories in sorted order with their total sales
        for category, sales in sorted(categorycounts.items()):
            print('Total sales for', category, 'in 2015:', sales, file=reportfile)

        print('-'*80, file=reportfile) # Separator line between categories and total

        # Sum and print total sales to both file and screen
        totalsales = sum(categorycounts.values())
        print("Total sales for the company in 2015:", totalsales, file=reportfile)
        print("Total sales for the company in 2015:", totalsales)

if __name__ == '__main__':
    main()

它是一个文本文件,不是csv,所以我不能在这里使用它。@Reginald:你确定吗?扩展名是.txt,但看起来像CSV(逗号分隔值)数据。很可能是有人从Excel或其他文件中保存为CSV,但使用了错误的扩展名;不过,只要内容正确,实际的扩展名并不重要。是的,实际上我们收到了一个.txt文件,并且被特别告知要使用它。@Reginald:我想说的是,不管扩展名是什么,如果文件包含CSV数据(您的示例就是这样),那么它就是CSV。扩展不重要。它可以是
.foobarbaz
,只要内容是CSV,您就可以这样使用它;
csv
模块甚至看不到文件名(它像文件一样包装对象,甚至不打开文件本身)。感谢您的澄清。有没有一种方法可以在不导入csv的情况下执行此操作?我知道这种方法非常优雅,而且切中要害,但到目前为止,我们还没有学会csv。