编写代码,实现商品搜索的功能
时间: 2024-01-13 12:04:26 浏览: 19
好的,我可以给你提供一个简单的商品搜索代码的实现示例。首先,你需要一个包含商品信息的数据集,例如一个CSV文件。然后,你需要使用Python编写一个程序来读取这个文件,并实现商品搜索功能。下面是一份示例代码:
```python
import csv
# 读取CSV文件
with open('products.csv', mode='r') as file:
reader = csv.DictReader(file)
products = [row for row in reader]
# 实现商品搜索功能
def search_products(query):
results = []
for product in products:
if query.lower() in product['name'].lower():
results.append(product)
return results
# 通过调用search_products函数来搜索商品
query = input('请输入要搜索的商品名称:')
results = search_products(query)
if results:
for result in results:
print(result)
else:
print('未找到相关商品')
```
这段代码假设你的商品信息存储在名为`products.csv`的CSV文件中,并且该文件包含以下列:`name`(商品名称)、`description`(商品描述)、`price`(商品价格)等。程序首先读取CSV文件并将其存储为一个Python列表。接着,它定义了一个名为`search_products`的函数,该函数使用`query`参数作为搜索关键词,并在商品列表中查找匹配的商品。最后,程序通过调用`search_products`函数来搜索商品,并输出搜索结果。