如何实现不区分大小写的 Python 搜索用户输入
你好,我有一个用Python写的搜索功能,它运行得很好。然后我还有一个用tkinter做的图形界面,可以接受用户输入。用户输入的内容会用来查询数据库,Python会根据输入来匹配记录。比如说,如果用户输入“blue”,它应该能匹配到“blue”和“Blue”这些记录。但是现在它只能匹配完全相同的,比如“blue”只能匹配“blue”,不能匹配“Blue”。有没有人知道怎么解决这个问题?下面是我已经写好的一个例子(注意,这只是一个假设的场景);
def Search():
global E1, E2, E3, E4, file
#Open the file in read mode
file = sqlite3.connect('H:\\matching.db')
#Welcome message
print ("Please type in the information required")
window = Tk()
window.title ("Search for matches")
def QuitSearch():
window.destroy()
#Create text that will be shown to the user
window.configure(bg="red")
Label(window, text="Please enter the colour of your hair").grid(row=0)
Label(window, text="Please enter the colour of your eyes").grid(row=1)
Label(window, text="Please enter your gender").grid(row=2)
Label(window, text="Please enter your shoe size").grid(row=3)
#Create where the user will input
E1= Entry(window)
E2= Entry(window)
E3= Entry(window)
E4= Entry(window)
#Assigning the input boxes to area on the screen
E1.grid(row=0, column=1)
E2.grid(row=1, column=1)
E3.grid(row=2, column=1)
E4.grid(row=3, column=1)
button = Button(window, text = "Submit information", command=Submit, fg="yellow", bg="black")
button.grid(row=3, column=2, padx = 5)
quitbutton = Button (window, text ="QUIT", command=QuitSearch, fg ="red")
quitbutton.grid(row=3, column=3, padx=5)
#The submit function allows the data inserted by the user in Search to be submitted and to search the database
def Submit():
global E1, E2, E3, E4, file
#Retaining user input
eyecolour = E1.get()
haircolour = E2.get()
gender = E3.get()
shoesize = E4.get()
#The search
cursor = file.execute ('''SELECT ID, forename, surname, FROM people
WHERE eyecolour =? and haircolour=? and gender=? and shoesize=? ''', (eyecolour, haircolour, gender, shoezize))
window=Tk()
def QuitOutputScreen():
window.destroy()
for row_number, row in enumerate(cursor):
Label(window, text ="ID = "+ str(row[0])).grid(row=1, column = row_number)
Label(window, text ="Forename = "+str(row[1])).grid(row=2, column = row_number)
Label(window, text ="Surname = "+(row[2])).grid(row=3, column = row_number)
Label(window, text ="Search complete ").grid(column=11)
quitbutton = Button (window, text ="QUIT", command=QuitOutputScreen, fg ="red")
quitbutton.grid(row=11, column=11, padx=5)
file.close()
2 个回答
0
在你的Python代码中,你可以使用字符串的lower和upper函数来存储和搜索小写或大写字母,或者你也可以使用正则表达式和re.IGNORE_CASE来进行搜索。
对于数据库查询,你可以选择把所有内容都存储成固定的大小写,或者告诉数据库引擎忽略大小写。
1
这个问题看起来更像是跟数据库管理系统(在这里是sqlite)有关,而不是直接跟Python有关。
你可以通过在sqlite中使用不区分大小写的搜索查询来解决这个问题。你可以在这个链接找到一些解释:如何设置Sqlite3在字符串比较时不区分大小写?。