Python 如何在csv文件中找到多个字符串

Python 如何在csv文件中找到多个字符串,python,python-3.x,csv,Python,Python 3.x,Csv,因此,我正在尝试学习python,并有一个类似这样的csv文件 1 product_id product_name price 2 1001 cake 15 3 1002 sprite 30 4 1003 coffee 50 5 1004 ice cream 30 6 1005 banana 10 我的节目是 import csv productid=input("Enter the product ID: ")

因此,我正在尝试学习python,并有一个类似这样的csv文件

 1  product_id  product_name    price
 2  1001    cake    15
 3  1002    sprite  30
 4  1003    coffee  50
 5  1004    ice cream   30
 6  1005    banana  10
我的节目是

import csv

productid=input("Enter the product ID: ")
quantity=int(input("Enter the quantity: "))
csv_file=csv.reader(open("shoppinglist.csv", "r"),delimiter=",")

for row in csv_file:
    if productid==row[0]:
        product_id=row[0]
        product_name=row[1]
        product_price=row[2]
        print("\nProduct ID: {}".format(row[0]))
        print("Product Name: {}".format(row[1]))
        print("Product Price: {}".format(row[2]))

total=quantity*(int(product_price))
print("\nThe Total Amount Payable is: {}".format(total))
我可以一次输入一个productid并获得输出,但我正在寻找一种方法,以便我可以输入多个productid的广告,在csv文件中搜索它们,然后计算总数并输出所有产品详细信息

PS:我已经尽可能地解释了我的问题,但是如果我犯了任何错误,请告诉我

我的输出是

输入产品ID:1001输入数量:5

产品编号:1001产品名称:蛋糕产品价格:15

应付总额为:75


我只是不想打印产品,而是想在csv文件中搜索其id,如果它存在,请用户输入输入的每个产品id的数量,然后打印产品的详细信息以及总数量。

您只需按照自己的方式解析输入。比如说,

def product(id): # given product id, returns price, 0 if item does not exist
    # your code goes here

id = input("Enter your product ids separated by spaces: ") # For e.g. 2 3 1
id = id.split(" ")

total = 0
for i in id:
    price = product(id)
    if price != 0:
        quantity = print("Enter quantity of " + str(id) + ": ")
        total += quantity*price

print("The total price is: " + price)

此代码解析ID,使其位于数组中。然后它遍历数组中的每个id并执行您的代码。

您应该仔细研究pandas,这将使所有这些类型的操作更加简单


每次提供产品Id时,您都需要一个循环来查看您的产品 我希望您理解以下代码

#作者姓名:Sandip Sadhukhan
导入csv
def findProduct(产品ID):
csv_file=csv.reader(打开('shoppinglist.csv','r'),分隔符=',')
产品价格=0
产品名称=“”
isFound=False
对于csv_文件中的行:
如果productId==行[0]:
productName=行[1]
productPrice=第[2]行
isFound=True
打破
结果={
“isFound”:isFound,
“产品名称”:产品名称,
“productPrice”:productPrice,
“productId”:productId
}
返回结果
总数=0
打印列表=[]
虽然(正确):
productid=输入(“输入产品Id:”)
结果=findProduct(productid)
如果没有(结果['isFound']):
打印(“未找到产品…”)
持续
数量=整数(输入(“输入数量:”)

如果(数量你能提供样本预期的输入和输出吗?输出是:输入产品ID:1001输入数量:5产品ID:1001产品名称:蛋糕产品价格:15应付总额是:75输入产品ID除以空格,然后使用
str.split()
获取带有id的列表,您可以在条件中使用下一个代码:
any(id==productids中id的行[0])
行[0]在productid中
。我只是不想打印产品,而是想在csv文件中搜索其id,如果它存在,请用户输入输入的每个productid的数量,然后打印产品的详细信息以及总数量。@RameezRazaRiaz我编辑了我的答案。希望我能帮上忙!感谢反馈人。这会是po吗可能只显示输入了productid的输出,而不显示整个文件,因为文件很长?只需执行df[df['qty']!=0]
    # Author Name : Sandip Sadhukhan

    import csv


    def findProduct(productId):
        csv_file = csv.reader(open('shoppinglist.csv', 'r'), delimiter=',')
        productPrice = 0
        productName = ''
        isFound = False
        for row in csv_file:
            if productId == row[0]:
                productName = row[1]
                productPrice = row[2]
                isFound = True
                break
        result = {
            'isFound': isFound,
            'productName': productName,
            'productPrice': productPrice,
            'productId': productId
        }
        return result


    total = 0
    printList = []
    while(True):
        productid = input("Enter a product Id: ")
        result = findProduct(productid)
        if not(result['isFound']):
            print("Product is not found...")
            continue

        quantity = int(input("Enter the quantity: "))
        if(quantity <= 0):
            print("Please select atleast 1 quantity.")
            continue
        total += quantity * (int(result['productPrice']))
        temp = [result['productName'], quantity, result['productPrice']]
        printList.append(temp)
        addMore = input("Add more Items? (Y/N) : ")
        if(addMore.lower() == 'n'):
            break

    print("\nBill\n====\n\n[Product Name] [Product Price] [Quantity]")
    for item in printList:
        print("{}  {}  {}".format(item[0], item[2], item[1]))
    print("The total Amount payable is : {}".format(total))