【问题标题】:read specific data in CSV读取 CSV 中的特定数据
【发布时间】:2017-07-12 18:02:55
【问题描述】:

我编写了一个代码,它读取作为输入给出的产品并给出产品价格的输出

data.csv 文件

1, 4.00, teddy_bear
1, 8.00, baby_powder
2, 5.00, teddy_bear
2, 6.50, baby_powder
3, 4.00, pampers_diapers
3, 8.00, johnson_wipes
4, 5.00, johnson_wipes
4, 2.50, cotton_buds
5, 4.00, bath_towel
5, 8.00, scissor
6, 5.00, scissor
6, 6.00, bath_towel, cotton_balls, powder_puff

python 代码

import csv

with open('data.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    usrid = []
    price = []
    product = []
    for row in readCSV:
        usrid.append(row[0])
        price.append(row[1])
        product.append(row[2])

    askProduct = raw_input('What Product do you wish to know the price of?:')
    abc = product.index(askProduct)
    thePrice = price[abc]
    print ('the price of product',askProduct, 'is', thePrice)

产生错误

Traceback (most recent call last):
File "C:/Users/Desktop/program.py", line 15, in <module>
abc = product.index(askProduct)
ValueError: 'teddy_bear' is not in list

需要以下输出

Program Input
program data.csv teddy_bear baby_powder

Expected Output

=> 2(userid), 11.5(addition of two products)

【问题讨论】:

  • 如果您打印出您的清单,您会注意到产品名称前面有空格。这就是您无法正确搜索它们的原因

标签: python python-2.7 csv


【解决方案1】:

您的 CSV 中有一个额外的空间,因此您的产品实际上是 " teddy_bear"。 Python 的 csv.reader() 允许您使用 skipinitialspace 参数告诉它忽略分隔符周围的多余空格:

csv.reader(csvfile, delimiter=',', skipinitialspace=True)

【讨论】:

    【解决方案2】:

    您需要去掉行中每个单元格之前的空格。由于分隔符是 ', 并且您的数据文件在每个 "," 之后都有一个空格

    import csv
    
    with open('data.csv') as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        usrid = []
        price = []
        product = []
        for row in readCSV:
            usrid.append(row[0].strip())
            price.append(row[1].strip())
            product.append(row[2].strip())
    
        askProduct = raw_input('What Product do you wish to know the price      of?:')
        abc = product.index(askProduct)
        thePrice = price[abc]
        print ('the price of product',askProduct, 'is', thePrice)
    

    【讨论】:

      【解决方案3】:

      您的代码不仅失败,而且空格,您还错过了最后一个以逗号分隔的产品。这是我的建议

      import csv
      
      with open('data.csv') as csvfile:
          readCSV = csv.reader(csvfile, delimiter=',')
          usrid = []
          price = []
          product = []
          for row in readCSV:
              # tmp_products =  row[2].split().strip()
              for the_product in row[2::]:
                  usrid.append(row[0])
                  price.append(row[1])
                  product.append(the_product.strip())
      
      askProduct = raw_input('What Product do you wish to know the price of?: ')
      abc = product.index(askProduct)
      thePrice = price[abc]
      print ('the price of product',askProduct, 'is', thePrice)
      

      而且你有相同的产品价格不同,所以代码可能是这样的:

      import csv
      
      with open('data.csv') as csvfile:
          readCSV = csv.reader(csvfile, delimiter=',')
          usrid = []
          price = []
          product = []
          for row in readCSV:
              # tmp_products =  row[2].split().strip()
              for the_product in row[2::]:
                  usrid.append(row[0].strip())
                  price.append(row[1].strip())
                  product.append(the_product.strip())
      
      askProduct = raw_input('What Product do you wish to know the price of?: ')
      abc = [i for i, x in enumerate(product) if x == askProduct]
      thePrice = [ price[p] for p in abc]
      print ('the price of product',askProduct, 'is', thePrice)
      

      更新

      import csv
      
      with open('data.csv') as csvfile:
          readCSV = csv.reader(csvfile, delimiter=',', skipinitialspace=True)
          usrid = []
          price = []
          product = []
          for row in readCSV:
              for the_product in row[2::]:
                  usrid.append(row[0])
                  price.append(float(row[1]))
                  product.append(the_product)
      
      askProduct = raw_input('What Product do you wish to know the price of?: ')
      abc = [i for i, x in enumerate(product) if x == askProduct]
      thePrice = [price[p] for p in abc]
      print ('the price of product',askProduct, 'is', min(thePrice))
      

      【讨论】:

      • 然后如何将产品的两个价格相加,它以字符串形式给出结果,例如:product1 teddy_bear 的价格是 ['4.00', '5.00'] product2 baby_powder 的价格是['8.00','6.50'] 我想添加两个产品 product1 和 product2 并给出最小数量
      • 要以数字形式使用,您只需将price.append(row[1].strip()) 更改为price.append(float(row[1].strip())),然后只需使用min(thePrice)min( [ price[p] for p in abc]) 即可获得最小值
      【解决方案4】:

      我会准确检查您的列表是如何组成的,由于 CSV 的构造方式,您的产品数组很可能类似于 [' teddy_bear', ' baby_powder'] 等。解决这个问题的一种方法是尝试

      usrid.append(row[0].strip())
      

      添加时应该去掉空格

      【讨论】:

        【解决方案5】:

        它并不完美,但它的工作方式如你所愿。

        import argparse
        import csv
        
        parser = argparse.ArgumentParser(description='What Product do you wish to know the price of?:')
        
        parser.add_argument('csvFileName',metavar='f', type=str,
                           help='a csv file with , as delimiter')
        parser.add_argument('item1',  type=str,
                           help='a first item')
        parser.add_argument('item2',  type=str,
                           help='a second item')
        
        args = parser.parse_args()
        
        with open(args.csvFileName) as csvfile:
            readCSV = csv.reader(csvfile, delimiter=',')
        
            listOfProduct = []
            #Fetch csv
            for row in readCSV:
                item = (row[0].replace(' ', ''), row[1].replace(' ', ''), row[2].replace(' ', ''))  
                listOfProduct.append(item)
        
            #Find all user corresponding with product
            item1found = [product for product in listOfProduct if product[2] == args.item1]
            item2found = [product for product in listOfProduct if product[2] == args.item2]
        
            allUserProducts = []    
            #Find item1 that corresponding with item2
            for item in item1found:
                (userId, price, product) = item
                otherUserProducts = [product for product in item2found if product[0] == userId]
                otherUserProducts.append(item)
        
                allUserProducts.append(otherUserProducts)
        
            for userProducts in allUserProducts:
                totalPrice = 0
        
                for product in userProducts:
                    (userId, price, product) = product
                    totalPrice += float(price)
        
                print '(' + str(userId) + ')','(' + str(totalPrice)+ ')'
        

        【讨论】:

          猜你喜欢
          • 2014-12-15
          • 2020-03-11
          • 1970-01-01
          • 2020-08-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多