使用python从.txt文件中提取信息,并按客户和产品对数字求和

2024-04-30 03:42:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下文本文件:

Customer   Product   Amount
Lynn        MAF       1750
Lynn        HAR       1950
Ken         RSF       1350
Dave        MAF       1000

我需要使用Python从这个文本文件中提取产品数量,并按客户名称求和,按产品代码求和。 期望的输出应该如下所示:

按客户名称列出的金额应打印出来:

Lynn 3700 
Ken 1350
Dave 1000

按产品代码列出的金额应打印出来:

MAF 2750
HAR 1950
RSF 1350

这是我的代码:

f2 = open("transactions.txt", "r")          #open and read transactions.txt file
headers2 = f2.readline()
data2 = f2.readlines()
print(headers2)
reportList = {}
for line in data2:
    line_split = line.split()
    reportList[line_split[0]] = [line_split[1],line_split[2]]#,line_split[3]]

grouping_choice = input("How would you like to group the sales - [P]: by product or [C]: by customer?").lower()
if grouping_choice == "p":                       #product grouping
    print(f'Product \t\t Total Sales')
   
    menu()                                     

elif grouping_choice == "c":                     #customer grouping
    print(f'Customer \t\t Total Sales')

    menu()
else:
    print("Error, you selected an invalid choice!")       #invalid selection, sends back to report menu
    report()

Tags: 代码linecustomerproductf2menusplitprint
1条回答
网友
1楼 · 发布于 2024-04-30 03:42:21

我认为最好的办法是有两本不同的字典

name_amount_map = {}
code_amount_map = {}
with open('transactions.txt', 'r') as file:
    header = file.readline()
    for line in file.readlines():
        name, code, amount = line.split()
        name_amount_map[name] = name_amount_map.get(name, 0) + int(amount)
        code_amount_map[code] = code_amount_map.get(code, 0) + int(amount)

i = input("How would you like to group the sales - [P]: by product or [C]: by customer?").lower()
if i == 'c':
    print(name_amount_map)
elif i == 'p':
    print(code_amount_map)

相关问题 更多 >