以CSV格式读取特定数据

时间:2017-07-12 18:02:56

标签: python python-2.7 csv

我编写了一个代码,用于读取作为输入的产品并提供产品价格的输出

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)

5 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

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

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)

答案 2 :(得分:0)

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

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

在添加

时应删除空格

答案 3 :(得分:0)

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

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))

答案 4 :(得分:0)

它并不完美,但它的工作方式与你想要的一样。

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)+ ')'