csv 使用索引打印数据集中的信息字符串

h7appiyu  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(107)

我正在尝试编写代码,以便在数据集中获取用户输入的菜肴的索引,然后打印包含菜肴信息的行中的所有内容。
这是我目前掌握的代码

import csv

myfile=open('indian_food.csv','r')

def read_dish(myfile):

    dish=input('What is the dish?\n')
    index=myfile.index(dish)
    for row in myfile:
        line_count=index
        print(f'\t{row['dish name']} is made of{row['ingredients']} and is a {row['diet']} dish. It takes {row['cook_time']} to cook. It is a {row['flavor_profile']} {row['course']} from the state of {row['state']}. Which is from the {row['region']} of India.')

然后从data set这样的数据集中提取数据(indian_foods.csv)而我需要得到这个作为一个例子“Pithe是用米粉,小麦粉做的,是一道素菜,烹饪需要35分钟,是来自阿萨姆邦的一种甜味甜点,即印度东北地区。”这基本上是从一个选择中组合所有信息。我需要能够对用户输入的行执行此操作。

sshcrbum

sshcrbum1#

我强烈建议用Pandas来做这个。它是为table量身定做的(dataframes)的数据。我不得不复制您的数据集作为几个例子,因为它是图片形式,所以您应该不必使用我的一些代码。如果您可以将您的数据放入dataframe,有大量的在线资源介绍如何做到这一点,那么这个应该可以用。Pandas中有一个函数叫做read_csv(),它可能会在一行代码中为你完成这个任务。

import pandas as pd

def read_dish(dataframe):
    dish=input('What is the dish?\n')
    row_index = (dataframe['dish name'] == dish).argmax()
    row = dataframe.iloc[row_index]
    print(f"{row['dish name']} is made of {row['ingredients']} and is a {row['diet']} dish. It takes {row['cook_time']} to cook. It is a {row['flavor_profile']} {row['course']} from the state of {row['state']}. Which is from the {row['region']} of India.")

    
# ---------- This code is only here to replicate your example ----------
data = [['dish name', 'ingredients', 'diet', 'cook_time', 'flavor_profile', 'course', 'state', 'region'],
       ['Balu shahi', 'Maida flour, yogurt, oil, sugar', 'vegetarian', 25, 'sweet', 'dessert', 'West Bengal', 'East'],
       ['Boondi', 'Gram flour, ghee, sugar', 'vegetarian', 30, 'sweet', 'dessert', 'Rajasthan', 'West'],
       ['Laddu', 'Gram flour, ghee, sugar', 'vegetarian', 40, 'sweet', 'dessert', -1, -1]]

df = pd.DataFrame(data)
headers = df.iloc[0].values
df.columns = headers
df.drop(index=0, axis=0, inplace=True)
# ----------------------------------------------------------------------

print(df)
read_dish(df)

输出

What is the dish?
 Boondi
Boondi is made of Gram flour, ghee, sugar and is a vegetarian dish. It takes 30 to cook. It is a sweet dessert from the state of Rajasthan. Which is from the West of India.

相关问题