繁体   English   中英

Python 从文本文件中提取数字和总数

[英]Python extract numbers from text file and total

我有一个名为 cart.txt 的 simple.txt 文件,它有 4 行文本和数字,全部用逗号分隔,即
23453, 1, 45.64, 白色, 手套
25753, 2, 78.32, 红色, 包
23346, 1, 24.54, 蓝色, 俱乐部
87653, 4, 76.12, 绿色, 球

我需要提取价格,然后求和。 到目前为止,我有:

with open("cart.txt", "r") as text_file:
    for line in text_file:
        part, quantity, price, desc1, desc2 = line.split(", ")[2]

total = sum([float(price) for price in line])
       

print("The total price for the awesome Fathers Day gifts you bought is ${}".format(total))

当我运行程序时,我收到一条错误消息,提示 python 无法将 str 转换为浮点数:','。
如果我删除零件、数量等并在包含 line.split 的那一行打印,我会收到所有 4 个价格,最后没有任何逗号。 为什么 python 添加逗号不允许我将其转换为浮点数? 任何帮助深表感谢。

当您这样做时,您正在同时进行destructuring assignments并按索引从list中获取项目

part, quantity, price, desc1, desc2 = line.split(", ")[2]

假定的string是文件的内容。

string = '''
23453, 1, 45.64, white, gloves
25753, 2, 78.32, red, bag
23346, 1, 24.54, blue, club
87653, 4, 76.12, green, ball
'''

lines = string.strip().split('\n')
prices = []

for line in lines:
  _, _, price, *_ = line.split(", ")
  prices.append(float(price))

print(sum(prices))

过滤所有价格,append 它们在一个列表中,然后对列表求和,如:

with open("cart.txt", "r") as text_file:
    all_the_price = [float(line.split(", ")[2]) for line in text_file]
    total = sum(all_the_price)
    print(total)
parts = []
quantities = []
prices = []
descs1 = []
descs2 = []

with open("cart.txt", "r") as text_file:
    for line in text_file:
        part, quantity, price, desc1, desc2 = line.strip().split(", ")

        parts.append(part)
        quantities.append(quantity)
        prices.append(float(price))
        descs1.append(desc1)
        descs2.append(desc2)

total = sum(prices)
print("The total price for the awesome Fathers Day gifts you bought is ${}".format(total))

这绝不是实现我认为你所追求的最有效的方法,但它应该可以帮助你理解这里所犯的错误。

每次阅读另一行时,您当前都在压倒price

在这里,我创建了一堆额外的列表,当您阅读文件时,将每条额外的数据附加到适当的列表中,最后求和是微不足道的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM