【问题标题】:how to seperate grouped items in sqlite3 through python如何通过python分隔sqlite3中的分组项目
【发布时间】:2022-01-27 20:16:07
【问题描述】:

iv 开始为我的程序使用数据库而不是 .txt 文件,我想做一个搜索功能

iv 了解了搜索功能的基础知识(包含所有可能选择的下拉菜单),但大多数项目在 1 列/行中有多个项目,例如

列“食物名称”“成分”“食谱”

           potato casserole    potato,cheese,ect

但在我的搜索功能土豆中,奶酪是 1 项,我该如何分离它??

我的第二个问题显然会有成分相似的食物,我怎样才能阻止它显示相同成分的倍数,并且仍然显示所有具有相同成分的食物的结果??

option 1 has cheese selected option 2 has potato and cheese selected ( but i want it to be seprated) option 3 at the top it shows cheese and at the buttom it shows cheese (from 2 differnt foods) and i want to only have 1 instance of that ingredient but return all the foods with that ingredient

from tkinter import *
from tkinter.ttk import Combobox
import sqlite3

con = sqlite3.connect("Food.db")
c = con.cursor()

c.execute("SELECT Ingredients FROM Dinner_Order")
order = c.fetchall()
c.execute("SELECT Ingredients FROM Dinner_Stove")
stove = c.fetchall()
c.execute("SELECT Ingredients FROM Dinner_Oven")
oven = c.fetchall()
c.execute("SELECT Ingredients FROM Dinner_Cold")
cold = c.fetchall()
c.execute("SELECT Ingredients FROM Dinner_Simple")
simple = c.fetchall()
con.commit()

dinner_order = order
dinner_stove = stove
dinner_oven = oven
dinner_cold = cold
dinner_simple = simple

ws = Tk()
ws.title("Python Guides")
ws.geometry("200x200")



item_names = dinner_order + dinner_stove + dinner_oven + dinner_simple + dinner_cold

combo = Combobox(ws, state='readonly')
combo['values'] = item_names
combo.pack()

combo = Combobox(ws, state='readonly')
combo['values'] = item_names
combo.pack()

combo = Combobox(ws, state='readonly')
combo['values'] = item_names
combo.pack()

combo = Combobox(ws, state='readonly')
combo['values'] = item_names
combo.pack()

button = Button(ws, text="search", )#command=search_items)
button.pack()

ws.mainloop()

【问题讨论】:

  • 很难就您提供的信息提供任何反馈。添加最小代码和示例数据

标签: python sqlite search


【解决方案1】:

我建议split, 上的结果,例如,如果查询返回"potato,cheese,ect",你会这样做:

"potato,cheese,ect".split(",")

类似这样的:

>>> c.execute("SELECT Ingredients FROM Dinner_Simple WHERE food_name ='potato casserole'")
>>> ingredients = c.fetchall()
>>> print(ingredients)
"potato,cheese,ect"
>>> ingredients = ingredients.split(",")
>>> print(ingredients)
["potato", "cheese", "ect"]

【讨论】:

  • 我如何在数据库中使用 .split(",")? (我使用数据库浏览器(SQlite)将所有信息添加到数据库中)
  • @ZFV6,我的意思是当您执行 SQL 查询并从数据库中检索数据时,您可以执行简单的split 将该字符串转换为列表。
  • 我需要使用“where”代码吗?因为每种食物都有多种成分,每种成分都有 40-50 种不同的食物,这比数据库的要点要好(加上用户可以选择添加更多的食物/成分/食谱,而那些不会出现在搜索下拉框中)和我的另一个问题是:是否可以删除相同成分的重复项?
  • 我必须先将其转换为字符串,然后才能将其拆分,然后使用土豆,奶酪的选项变为 ('potato and \n\rcheese 如何删除符号?
  • 不,您不需要使用where,这只是一个示例。要从列表中删除重复项,您可以将其转换为 set,这里有更多信息 stackoverflow.com/questions/15768757/… 删除 \n\r 等字符的最佳方法是使用正则表达式,或者您也可以使用 @987654332 @你的字符串上的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 2012-03-15
  • 2021-03-22
相关资源
最近更新 更多