簡體   English   中英

通過讀取Python中的文本文件來計算總數

[英]Calculate totals by reading from a text file in Python

我試圖用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年農民的銷售總額:{插入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文件,因此您可能應該使用pythons內置的csv模塊來解析該文件。 DictReader類將每一行變成字典,鍵為標題。 如果您的csv文件名為product_sales.csv ,則以下代碼將起作用。

import csv

product_dict = {}
cat_dict = {}
with open('product_sales.csv', 'r') as f:
    for line in csv.DictReader(f):
        cat = line['CATEGORY']
        product = line['PRODUCT']
        sales_15 = int(line['2015 Sales'])
        if cat in cat_dict:
            cat_dict[cat] += sales_15
        else:
            cat_dict[cat] = sales_15
        if product in product_dict:
            product_dict[product] += sales_15
        else:
            product_dict[product] = sales_15

Total = sum(cat_dict.values())
print product_dict
print cat_dict
print Total

您的代碼看起來是一個好的開始; 這里有一些提示:

  • 它是用一個好主意, with打開文件時,因為它保證他們將得到正確關閉。 代替

     productFile = open(PRODUCT_FILE, "r") # do something with the file productFile.close() 

    你應該做

     with open(PRODUCT_FILE, "r") as product_file: # do something with the file # the file has been closed! 
  • 您只需調用proData = extractDataRecord(productFile)一次(即,您獲得標題行,但沒有任何數據)。 您可以將其放在while循環中,但是直接在文件上進行迭代更慣用了,即

     for line in product_file: product, category, _, sales = line.split(',') sales = int(sales) # now do something with the values! 

    (使用_作為變量名是“我不在乎此值”的簡寫)

  • 您可以使用dict來跟蹤每種產品的產品和總銷售額,

     product_sales = {} 

    然后在for循環中

     product_sales[product] = product_sales.get(product, 0) + sales 

    如果您可以from collections import defaultdictfrom collections import defaultdict變得更加簡單:

     product_sales = defaultdict(int) product_sales[product] += sales 
  • 處理完整個文件后,您需要報告以下結果:

     all_sales = 0 for product, sales in product_sales.items(): # write the sales for this product all_sales += sales # print all_sales 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM