如何创建在CSV文件中搜索的函数?

2024-04-23 15:07:00 发布

您现在位置:Python中文网/ 问答频道 /正文

写一个函数来读取一个CSV文件,鲜花.csv地址:

petunia,5.95
alyssum,3.95
begonia,5.95
sunflower,5.95
coelius,4.95

查一查花的价格然后打印出来。你知道吗

import csv

def problem3_7(csv_pricefile, flower):

  f = open(csv_pricefile) 

  for row in f:
    if row[0] == flower:
      print (row[1])    

  f.close() 

我考虑将CSV文件转换成一个字典,这样通过搜索一朵花就可以给出价格。我相信有一个更好的方法通过比较行来做到这一点,但我似乎不知道怎么做。你知道吗

一行将由例如petunia, 5.95而不仅仅是petunia组成,这意味着我不能比较rows == flower。我试着用row[0][0],因为它只指花的名字,但对我来说并不管用。你知道吗

还有。。。我认为我应该使用一些csv功能,我目前没有这样做。你知道吗

有人能帮我解决这个问题吗?你知道吗


Tags: 文件csv函数地址价格rowflowersunflower
3条回答

可以这样使用pandas

import pandas as pd
with open(csv_pricefile, 'r') as pricefile:
    df = pd.read_csv(pricefile, names=['flower', 'price'], index_col=0)
    data = df.to_dict(orient='index')
    # now you can get the price
    print(data[flower]['price'])

您可以使用csv.reader和字典理解来构建花名和价格之间的映射:

from io import StringIO
import csv

mystr = StringIO("""petunia,5.95
alyssum,3.95
begonia,5.95
sunflower,5.95
coelius,4.95""")

# replace mystr with open(csv_pricefile)
with mystr as fin:
    reader = csv.reader(fin)
    flower_prices = {name: float(price) for name, price in reader}

print(flower_prices)

{'alyssum': 3.95,
 'begonia': 5.95,
 'coelius': 4.95,
 'petunia': 5.95,
 'sunflower': 5.95}

然后通过字典提取特定花的价格,例如矮牵牛花使用flower_prices['petunia']。你知道吗

您将花与第一个角色进行比较,而不是组件。尝试使用:

    for row in f:
        cols = row.split(',')
        if cols[0].strip() == flower:
            print (cols[1].strip())    

相关问题 更多 >