[英]How to save a tuple in a Textfile and access it with this code in Python
I really want to finish my personal vocabulary trainer. 我真的很想完成我的个人词汇培训师。 It works fine, but I am having problems with saving the list into a text file and access it, after exiting the program. 它工作正常,但是退出程序后,我在将列表保存到文本文件并访问它时遇到了问题。
Please note that I am a beginner in Python, so it would be great, if I could have an explanation for the solution. 请注意,我是Python的初学者,所以如果可以对解决方案进行解释,那将很棒。 Thanks 谢谢
Here´s my code so far: 到目前为止,这是我的代码:
import random
import os
class Entry:
def __init__(self, deutsch, englisch):
self.deutsch = deutsch
self.englisch = englisch
def toString(self):
return self.deutsch + " - " + self.englisch
eintraege = [Entry("hallo", "hello")] **<--Wanna save this list**
directory = r'C:\Users\Peter\desktop'
def eingabe(): #means 'input' in english
while True:
deutsch = input("Deutsches Wort: ")
if deutsch == '#exit#':
return
englisch = input("Englisches Wort: ")
if englisch == '#exit#':
return
eintraege.append(Entry(deutsch, englisch))
w = open('dictionary.txt', 'a')
w.write(' - '.join(eintraege)) **<---------Problem here; tried multiple solutions**
def abfrage(): #means 'query' in english
while True:
i = random.randint(0, len(eintraege) - 1)
englisch = input("Englische Übersetzung von " + eintraege[i].deutsch + ": ")
if englisch == '#exit#':
return
if eintraege[i].englisch == englisch:
print("Korrekt!")
else:
print("Leider falsch. Richtig wäre:", eintraege[i].englisch)
def printall():
for eintrag in eintraege:
print(eintrag.toString)
os.chdir(directory)
r = open('dictionary.txt', 'r')
r.read()
while True:
print("Befehle:\n\
1.) eingabe: Ermöglicht die Bearbeitung des Wörterbuchs\n\
2.) abfrage: Zufällige Abfrage der Vokabel\n\
3.) ausgabe: Zeigt alle eingegebenen Vokabel an\n\
4.) beenden: Beendet das Programm\n\n")
befehl = input("Befehl: ")
if befehl == 'eingabe':
eingabe()
elif befehl == 'abfrage':
abfrage()
elif befehl == 'beenden':
break
elif befehl == 'ausgabe': #means 'output' in english
printall()
else:
print("Kein bekannter Befehl!")
I am grateful for any help. 感谢您的帮助。
You are outputting the wrong data. 您输出的数据错误。 Instead of 代替
eintraege.append(Entry(deutsch, englisch))
you want: 你要:
eintraege.append( Entry(deutsch, englisch).toString() )
or just: 要不就:
eintraege.append( deutsch + '-' + englisch )
Python does not recognize the "Entry" type and will not automatically convert it to a string, so you need to fill you list with strings, NOT Entry objects. Python无法识别“ Entry”类型,并且不会自动将其转换为字符串,因此您需要在列表中填充字符串,而不是Entry对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.