簡體   English   中英

讀取CSV中的特定數據

[英]read specific data in 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)

CSV中有多余的空間,因此您的產品實際上是" teddy_bear" Python的csv.reader()允許您使用skipinitialspace參數告訴它忽略分隔符周圍的多余空格:

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

您需要刪除行中每個單元格之前的空間。 由於定界符為',',並且您的數據文件在每個“,”之后都有一個空格

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)

我會檢查一下清單的組成方式,由於CSV的構造方式,您的產品數組很有可能像[' teddy_bear', ' baby_powder']等。 解決此問題的一種方法是嘗試

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

添加時應該刪除空格

您的代碼不僅失敗,而且失敗了,您還錯過了逗號分隔的最后一個產品。 這是我的建議

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)

UPDATE

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

它不是完美的,但是可以按您想要的方式工作。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM