如何使用文本文件中的信息创建购物报告
How to create a shopping report using information from a text file
像这样
购物报告
名字 1
Thing1 number1 cost1
Thing11 number11 cost11
支付金额
名字2
Thing2 number2 cost2
Thing22 number22 cost22
要支付的金额
文本文件
Petrov 钢笔 10 151000
波尔佐夫纸 20 20000
Butar case-bos 5 5000
Semerik pen2 500 250000
彼得罗夫钢笔(油) 100 10000
波尔佐夫纸 40 40000
Butar 书 5 15000
Semerik 帽子 500 250000
你会这样做:
path = "C:\Users\User\AppData\Local\Programs\Python\Python38\Stack overflow\textfile.txt"
newpath = "C:\Users\User\AppData\Local\Programs\Python\Python38\Stack overflow\textfileout.txt"
text = open(path, "r")
textinfo = text.readlines()
dictofinfo = {}
for line in textinfo:
line = line.strip()
lineaslist = line.split(" ")
name = lineaslist[0]
if not(name in dictofinfo.keys()):
dictofinfo[lineaslist[0]] = [lineaslist[1:]]
else:
dictofinfo[lineaslist[0]].append(lineaslist[1:])
text.close()
out = open(newpath, "w")
for entry in dictofinfo:
totaltobepayed = 0
out.write(entry + "\n")
for seperateentry in dictofinfo[entry]:
totaltobepayed += int(seperateentry[2])
out.write(" ".join(seperateentry) + "\n")
out.write(str(totaltobepayed) + "\n")
out.close()
将路径变量替换为您的文本文件的路径。
像这样
购物报告
名字 1
Thing1 number1 cost1
Thing11 number11 cost11 支付金额
名字2
Thing2 number2 cost2
Thing22 number22 cost22
要支付的金额
文本文件
Petrov 钢笔 10 151000
波尔佐夫纸 20 20000
Butar case-bos 5 5000
Semerik pen2 500 250000
彼得罗夫钢笔(油) 100 10000
波尔佐夫纸 40 40000
Butar 书 5 15000
Semerik 帽子 500 250000
你会这样做:
path = "C:\Users\User\AppData\Local\Programs\Python\Python38\Stack overflow\textfile.txt"
newpath = "C:\Users\User\AppData\Local\Programs\Python\Python38\Stack overflow\textfileout.txt"
text = open(path, "r")
textinfo = text.readlines()
dictofinfo = {}
for line in textinfo:
line = line.strip()
lineaslist = line.split(" ")
name = lineaslist[0]
if not(name in dictofinfo.keys()):
dictofinfo[lineaslist[0]] = [lineaslist[1:]]
else:
dictofinfo[lineaslist[0]].append(lineaslist[1:])
text.close()
out = open(newpath, "w")
for entry in dictofinfo:
totaltobepayed = 0
out.write(entry + "\n")
for seperateentry in dictofinfo[entry]:
totaltobepayed += int(seperateentry[2])
out.write(" ".join(seperateentry) + "\n")
out.write(str(totaltobepayed) + "\n")
out.close()
将路径变量替换为您的文本文件的路径。