【问题标题】:Python extract numbers from text file and totalPython从文本文件和总数中提取数字
【发布时间】:2020-08-21 01:35:01
【问题描述】:

我有一个名为 cart.txt 的简单 .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 添加逗号,不允许我将其转换为浮点数?非常感谢任何帮助。

【问题讨论】:

    标签: python text split


    【解决方案1】:

    过滤所有价格,将它们附加到列表中,然后对列表求和,例如:

    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)
    

    【讨论】:

    • 成功了!这基本上就是我所需要的。看起来我只需要在拆分后将 for 线向下移动,然后将其向后移动。非常感谢!
    【解决方案2】:
    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

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

    【讨论】:

      【解决方案3】:

      您正在执行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))
      

      【讨论】:

        猜你喜欢
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-13
        • 1970-01-01
        相关资源
        最近更新 更多