如何获取变量查找Txt文件中存储在字典中的值? [英] How Do I Get The Variable Find The Values Stored In The Dictionary In The Txt File?

查看:74
本文介绍了如何获取变量查找Txt文件中存储在字典中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from tkinter import *

# key press funciton:
def click():
    entered_text = entry.get() # collect text from the text entry box
    output.delete(0.0, END) # clear text box
    try:
        definition = my_glossary[entered_text]
    except:
        definition = "There is no entry for this word."
    output.insert(END, definition)

def clickNew():
    global my_glossary
    addToGlossary = entryNew.get()
    addToGlossaryDef = outputNew.get()
    my_glossaryOpen = open("glossary.txt", "a")
    #addToGlossaryTotal = {
        #addToGlossary : addToGlossaryDef 
        #}
    addToGlossaryTotal = (addToGlossary, ",", addToGlossaryDef)
    my_glossaryOpen.write(repr(addToGlossaryTotal))
    my_glossaryOpen.close()

def addNewClose():
    addNew.destroy()

def addNewWord():
    global addNew
    global entryNew
    global outputNew
    addNew = Tk()
    addNew.title("Add A New Word")
    
    # create label
    Label(addNew, text="Enter the word you are defining: ").grid(row=0, column=0, sticky=W)

    # create text entry box
    entryNew = Entry(addNew, width=20, bg="light blue")
    entryNew.grid(row=1, column=0, sticky=W)

    # Add a submit button
    Button(addNew, text="SUBMIT", width=5, command=clickNew).grid(row=2, column=0, sticky=W)

    # Add another button
    Button(addNew, text="Close", width=5, command=addNewClose).grid(row=0, column=3, sticky=W)

    # create another label
    Label(addNew, text="\nDefinition: ").grid(row=3, column=0, sticky=W)

    # create text entry box
    outputNew = Entry(addNew, width=75, bg="light blue")
    outputNew.grid(row=4, column=0, sticky=W)

    addNew.bind("<Return>", clickNew)
    
    addNew.mainloop()

#### main
window = Tk()
window.title("My Coding Club Glossary")

# create label
Label(window, text="Enter the word you want defining: ").grid(row=0, column=0, sticky=W)

# create text entry box
entry = Entry(window, width=20, bg="light green")
entry.grid(row=1, column=0, sticky=W)

# Add a submit button
Button(window, text="SUBMIT", width=5, command=click).grid(row=2, column=0, sticky=W)

# Add another button
Button(window, text="Add New Word", width=13, command=addNewWord).grid(row=0, column=1, sticky=W)

# create another label
Label(window, text="\nDefinition: ").grid(row=3, column=0, sticky=W)

# create text box
output = Text(window, width=75, height=6, wrap=WORD, background="light green")
output.grid(row=4, column=0, columnspan=2,sticky=W)

#The dictionary:
#my_glossaryOpen = open("glossary.txt", "r")
#my_glossary = my_glossaryOpen.read()
#my_glossaryOpen.close()
with open('glossary.txt','r') as inf:
    my_glossary = eval(inf.read())


## Binging the enter key
window.bind("<Return>", click)

#### Run mainloop
window.mainloop()





请回答t给出的问题他顶了...谢谢



我需要让my_glossary从txt文件中获取数据但是当我使用addNewWord函数添加数据时,我会收到诸如txt文件中的语法错误,指出{}或''是问题的原因。




please answer the question given at the top...thanks

I need to get my_glossary to get the data from the txt file but when I add the data using the addNewWord function I get errors such as a syntax error inside the txt file saying that the {} or '' are the cause of the issue.

from tkinter import *

def dictest():
    global my_glossary
# read all lines of the file
    inFile = open("glossary.txt", "r")
    inText = inFile.read()
    inFile.close()
 
    my_glossary = {}
# iterate through all lines, after removing the line-end character(s)
    for line in inText.splitlines():
        if line != '':           # ignore empty lines
            key,value = line.split(',')
            my_glossary[key] = value
 
    my_glossary['newkey'] = 'and the new value'
 
# list all the dictionary entries
    for k,v in my_glossary.items():
        print('key:', k, ', value:', v)

# key press funciton:
def click():
    entered_text = entry.get() # collect text from the text entry box
    output.delete(0.0, END) # clear text box
    try:
        definition = my_glossary[entered_text]
    except:
        definition = "There is no entry for this word."
    output.insert(END, definition)

def clickNew():
    global my_glossary
    addToGlossary = entryNew.get()
    addToGlossaryDef = outputNew.get()
    my_glossaryOpen = open("glossary.txt", "a")
    #addToGlossaryTotal = {
        #addToGlossary : addToGlossaryDef 
        #}
    addToGlossaryTotal = addToGlossary, addToGlossaryDef,
    my_glossaryOpen.write(repr(addToGlossaryTotal))
    my_glossaryOpen.close()

def addNewClose():
    addNew.destroy()

def addNewWord():
    global addNew
    global entryNew
    global outputNew
    addNew = Tk()
    addNew.title("Add A New Word")
    
    # create label
    Label(addNew, text="Enter the word you are defining: ").grid(row=0, column=0, sticky=W)

    # create text entry box
    entryNew = Entry(addNew, width=20, bg="light blue")
    entryNew.grid(row=1, column=0, sticky=W)

    # Add a submit button
    Button(addNew, text="SUBMIT", width=5, command=clickNew).grid(row=2, column=0, sticky=W)

    # Add another button
    Button(addNew, text="Close", width=5, command=addNewClose).grid(row=0, column=3, sticky=W)

    # create another label
    Label(addNew, text="\nDefinition: ").grid(row=3, column=0, sticky=W)

    # create text entry box
    outputNew = Entry(addNew, width=75, bg="light blue")
    outputNew.grid(row=4, column=0, sticky=W)

    addNew.bind("<Return>", clickNew)
    
    addNew.mainloop()

#### main
dictest()
window = Tk()
window.title("My Coding Club Glossary")

# create label
Label(window, text="Enter the word you want defining: ").grid(row=0, column=0, sticky=W)

# create text entry box
entry = Entry(window, width=20, bg="light green")
entry.grid(row=1, column=0, sticky=W)

# Add a submit button
Button(window, text="SUBMIT", width=5, command=click).grid(row=2, column=0, sticky=W)

# Add another button
Button(window, text="Add New Word", width=13, command=addNewWord).grid(row=0, column=1, sticky=W)

# create another label
Label(window, text="\nDefinition: ").grid(row=3, column=0, sticky=W)

# create text box
output = Text(window, width=75, height=6, wrap=WORD, background="light green")
output.grid(row=4, column=0, columnspan=2,sticky=W)

#The dictionary:
f = open("glossary.txt", "r")

num_lines = sum(1 for line in open("glossary.txt"))

def readLines():
    global my_glossary
    global line
    global words
    global f
    f = open("glossary.txt", "r")
    line = f.readline()
    words = line.split(",")
    my_glossary = {}
    my_glossary[words[0]]=words[1]
    line = f.readline()
    words = line.split(",")
    my_glossary[words[0]]=words[1]

while num_lines > 0:
    readLines()
    num_lines -=1

## Binging the enter key
window.bind("<Return>", click)

#### Run mainloop
window.mainloop()

推荐答案

请参阅以下内容阅读文本文件和创建字典。请注意,词汇表文件中的文本不需要引号。我的文件看起来像:

See the following for reading the text file and creating a dictionary. Note you do not need quotes around your text in the glossary file. My file looks like:
foo,something silly
bar,something sillier



代码


Code

f = open('glossary.txt','r')
line = f.readline()
words = line.split(',')
dict = {}
dict[words[0]]=words[1]
line = f.readline()
words = line.split(',')
dict[words[0]]=words[1]

dict    # show the dictionary content

# output
{'foo': 'something silly\n', 'bar': 'something sillier\n'}


def dictest():
# read all lines of the file
    inFile = open("glossary.txt", "r")
    inText = inFile.read()
    inFile.close()

    glossary = {}
# iterate through all lines, after removing the line-end character(s)
    for line in inText.splitlines():
        if line != '':           # ignore empty lines
            key,value = line.split(',')
            glossary[key] = value

    glossary['newkey'] = 'and the new value'

# list all the dictionary entries
    for k,v in glossary.items():
        print('key:', k, ', value:', v)


这篇关于如何获取变量查找Txt文件中存储在字典中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆