如何创建自定义字典输出当前拿起第一个字母并给出输出

问题描述

我正在尝试创建一个简单的首字母缩略词定义 GUI。我大部分时间都拥有它。我的目标是实现两种不同类型的输出。如果用户输入 A,我希望它输出所有以 A 开头的首字母缩略词,就会发生这种情况。例如,当我键入 ACL 时,它会再次带回所有首字母缩略词,而不仅仅是 ACL 首字母缩略词。我怀疑错误或非错误可能来自 .join

from tkinter import *
import tkinter.messageBox


HEIGHT = 400
WIDTH = 700


root = Tk()
root.title("Testing")


a_canvas = Canvas(root,height=HEIGHT,width=WIDTH)
a_canvas.pack()


def clicked():
    entered = a_entry.get()
    a_textBox.delete(0.0,END)
    try:
        textin = ",".join(loop_over_input(entered))
    except:
        textin = 'Sorry invalid information provided.\nResubmit with the correct information.\n'
    a_textBox.insert(0.0,textin)


def clr():
    a_entry.delete(0,'end')
    a_textBox.delete(0.0,'end')


# def gone():
#     tkinter.messageBox.showinfo("Goodbye",'Come back soon.')
#     exit()


# Keep this is the master code
def loop_over_input(the_str=''):
    master_list = []
    for char in the_str:
        tmp_char = passwordConversion[char]
        master_list.append(tmp_char)
    print("Master Pass List: ",master_list)
    return master_list


def cont():
    tkinter.messageBox.showinfo("About",'\n Wrote by Me \n Version 1.0 \n Python\Tkinter')


# Custom Dictionary
passwordConversion = {
    "A": "AWS - Amazon Web Services \nAmazon ES - Amazon Elasticsearch Service \nAMI - Amazon Machine Image \nAPI - Application Programming Interface \nAI - Artificial Intelligence \nACL - Access Control List \nARN - Amazon Resource Name \nAZ - Availability Zone \nASG - Auto Scaling Group \nAES - Advanced Encryption System \nADFS - Active Directory Federation Service","AWS": "Amazon Web Services","Amazon ES": "Amazon Elasticsearch Service","AMI": "Amazon Machine Image","API": "Application Programming Interface","AI": "Artificial Intelligence","ACL": "Access Control List","ARN": "Amazon Resource Name","AZ": "Availability Zone","ASG": "Auto Scaling Group","AES": "Advanced Encryption System","ADFS": "Active Directory Federation Service",}

# Creating the Frames
a_frame = Frame(root,bg='Red',bd=5)
a_frame.place(relx=0.5,rely=0.1,relwidth=0.75,relheight=0.1,anchor='n')

a_middle_frame = Frame(root,bg='White')
a_middle_frame.place(relx=0.5,rely=0.25,relheight=0.25,anchor='n')


# Creating entry Boxes
a_entry_var = StringVar()
a_entry = Entry(a_frame,font=20,textvariable=a_entry_var)
a_entry.place(relwidth=0.65,relheight=1)


# Create a text Box
a_textBox = Text(a_middle_frame,font=12)
a_textBox.place(relwidth=1.00,relheight=1)

# Creating button
a_button = Button(a_frame,padx=2,pady=2,text='Get Defination',command=clicked,bg='Silver',font=('Calibri 11 bold'))
a_button.place(relx=0.7,relheight=1,relwidth=0.3)


a_buttons_frame = Frame(root)
a_buttons_frame.place(relx=0.4,rely=0.6)


a_button2 = Button(a_buttons_frame,text='Clear Fields',font=('Calibri 11 bold'),command=clr)
a_button2.grid(column=0,row=0,padx=(20,20))

# a_button3 = Button(a_buttons_frame,text='Exit',command=gone,font=('none 18 bold'))
# a_button3.grid(column=1,0))


a_label = Label(text="- For Me Only - \n- Contains information for me only",)
a_label.pack(side='bottom')

# Define Menu Items
my_menu = Menu(root)
root.config(menu=my_menu)

# Create Menu Items
file_menu = Menu(my_menu)
my_menu.add_cascade(label="File",menu=file_menu)
file_menu.add_command(label="Exit",command=root.quit)

# Create another submenu Edit
edit_menu = Menu(my_menu)
my_menu.add_command(label="About",command=cont)

root.mainloop()

解决方法

就我而言,您在 loop_over_input 中以错误的方式检查它,这会导致显示正确输出的问题。

您应该从字典中获取键并检查每个键是否以用户文本 - startswith() 开头。它解决了错误输出的问题。

然后您就不需要 "A": "...",因为它会找到所有以 "A" 开头的项目。

当用户写入 .upper() 时,我也会使用 AWS 来获取 aws

def loop_over_input(the_str=''):
    master_list = []
    
    for key,value in passwordConversion.items():
        if key.upper().startswith(the_str.upper()):
            master_list.append(f'{key} - {value}')

    print("Master Pass List: ",master_list)
    return master_list

因为 master_list 有列表,所以我在

中使用 "\n" 而不是 ","
textin = "\n".join(loop_over_input(entered))

enter image description here

完整的工作代码,代码组织得更好。

import tkinter as tk  # PEP8: `import *` is not preferred
import tkinter.messagebox

# --- constants --- (PEP8: UPPPER_CASE_NAMES)

HEIGHT = 400
WIDTH = 700

# --- classes --- (PEP8: CamelCaseNames)

# ... empty ...

# --- functions --- (PEP8: lower_case_names)

def clicked():
    entered = a_entry.get()
    a_textbox.delete(0.0,'end')
    try:
        textin = "\n".join(loop_over_input(entered))
    except:
        textin = 'Sorry invalid information provided.\nResubmit with the correct information.\n'
    a_textbox.insert(0.0,textin)


def clr():
    a_entry.delete(0,'end')
    a_textbox.delete(0.0,'end')


# def gone():
#     tkinter.messagebox.showinfo("Goodbye",'Come back soon.')
#     exit()


# Keep this is the master code
def loop_over_input(the_str=''):
    master_list = []
    
    for key,master_list)
    return master_list


def cont():
    tkinter.messagebox.showinfo("About",'\n Wrote by Me \n Version 1.0 \n Python\Tkinter')

# --- main --- (PEP8: lower_case_names)

# - data -

# Custom Dictionary
passwordConversion = {
    #"A": "AWS - Amazon Web Services \nAmazon ES - Amazon Elasticsearch Service \nAMI - Amazon Machine Image \nAPI - Application Programming Interface \nAI - Artificial Intelligence \nACL - Access Control List \nARN - Amazon Resource Name \nAZ - Availability Zone \nASG - Auto Scaling Group \nAES - Advanced Encryption System \nADFS - Active Directory Federation Service","AWS": "Amazon Web Services","Amazon ES": "Amazon Elasticsearch Service","AMI": "Amazon Machine Image","API": "Application Programming Interface","AI": "Artificial Intelligence","ACL": "Access Control List","ARN": "Amazon Resource Name","AZ": "Availability Zone","ASG": "Auto Scaling Group","AES": "Advanced Encryption System","ADFS": "Active Directory Federation Service",}

# - code -

root = tk.Tk()
root.title("Testing")

a_canvas = tk.Canvas(root,height=HEIGHT,width=WIDTH)
a_canvas.pack()


# Creating the Frames
a_frame = tk.Frame(root,bg='Red',bd=5)
a_frame.place(relx=0.5,rely=0.1,relwidth=0.75,relheight=0.1,anchor='n')

a_middle_frame = tk.Frame(root,bg='White')
a_middle_frame.place(relx=0.5,rely=0.25,relheight=0.25,anchor='n')


# Creating entry boxes
a_entry_var = tk.StringVar()
a_entry = tk.Entry(a_frame,font=20,textvariable=a_entry_var)
a_entry.place(relwidth=0.65,relheight=1)


# Create a text box
a_textbox = tk.Text(a_middle_frame,font=12)
a_textbox.place(relwidth=1.00,relheight=1)

# Creating button
a_button = tk.Button(a_frame,padx=2,pady=2,text='Get Defination',command=clicked,bg='Silver',font=('Calibri 11 bold'))
a_button.place(relx=0.7,relheight=1,relwidth=0.3)


a_buttons_frame = tk.Frame(root)
a_buttons_frame.place(relx=0.4,rely=0.6)


a_button2 = tk.Button(a_buttons_frame,text='Clear Fields',font=('Calibri 11 bold'),command=clr)
a_button2.grid(column=0,row=0,padx=(20,20))

# a_button3 = tk.Button(a_buttons_frame,text='Exit',command=gone,font=('none 18 bold'))
# a_button3.grid(column=1,0))


a_label = tk.Label(text="- For Me Only - \n- Contains information for me only",)
a_label.pack(side='bottom')

# Define Menu Items
my_menu = tk.Menu(root)
root.config(menu=my_menu)

# Create Menu Items
file_menu = tk.Menu(my_menu)
my_menu.add_cascade(label="File",menu=file_menu)
file_menu.add_command(label="Exit",command=root.quit)

# Create another submenu Edit
edit_menu = tk.Menu(my_menu)
my_menu.add_command(label="About",command=cont)

root.mainloop()

PEP 8 -- Style Guide for Python Code


编辑:

我会使用 regex 来使用更复杂的搜索,即。 I$ 获取以 I 结尾的字符串。

最终我会使用 fnmatch 来搜索星号 - '*I''A*S'


带有 regex 的代码

import re

def loop_over_input(the_str=''):
    master_list = []
    
    for key,value in passwordConversion.items():
        #if re.match(the_str,key,re.I):  # check at the beginning of string
        if re.search(the_str,re.I):  # check in any place of string
            master_list.append(f'{key} - {value}')

    print("Master Pass List: ",master_list)
    return master_list

所有以 S 结尾的键

enter image description here