0

我是 Python 新手(也是 stackoverflow 的新手,你会很容易注意到它!)

我实际上正在尝试编写一个可以按如下方式工作的程序:用户启动程序。有人问他是否要输入一个新单词,以及该单词的翻译。单词及其翻译存储在文件 (data.txt) 中。当他完成添加新单词时,测验开始。该程序选择一个单词,并要求用户进行翻译。如果答案与文件中的翻译相似,则程序返回“Great !”,如果不是,则打印正确答案。

如您所见,这非常简单。我的问题是处理文件,尤其是检索文件中的内容并正确使用它。

这是我的代码:

#!/usr/bin/python3.2
# -*-coding:Utf-8 -*

#Vocabulary/translation quiz

import os
import random

keep_adding=input("Would you like to add a new word ? If yes, press \"O\" : ")
while keep_adding=="O":
    entry=[]
    word=input("Enter a word : ")
    word=str(word)
    entry.append(word)
    translation=input("And its translation : ")
    translation=str(translation)
    entry.append(translation)
    entry=str(entry)
    f = open("data.txt","a")
    f.write(entry)
    f.close()
    keep_adding=input("To continue, press \"O\" : ")

f = open("data.txt","a") #in case the file doesn't exist, we create one
f.close()

os.system('clear')
print("* * * QUIZ STARTS ! * * *")

f = open("data.txt","r")

text = f.readlines()
text = list(text)
print("What is the translation for : ",text[0], "?")
answer = input("Answer : ")
if (answer == text[1]):
    print("Congratulations ! That's the good answer !")
else:
    print("Wrong. The correct answer was : ",text[1])

非常感谢你的帮助 !

编辑:确实对我的代码进行了一些更正。我得到的是以下内容:

    * * * QUIZ STARTS ! * * *
What is the translation for :  ['alpha', 'bravo']['one', 'two']['x', 'y'] ?
Answer : alpha
Traceback (most recent call last):
  File "Python_progs/voc.py", line 43, in <module>
    if (answer == text[1]):
IndexError: list index out of range

在我的文件中,我有这个:

['alpha', 'bravo']['one', 'two']['x', 'y']

所以实际上,我只想得到问题中的第一个词(即 alpha),并且在回答 bravo 时,把它做对。

4

3 回答 3

1

您也可以这样做;这不需要外部文件:)

###   WORDLIST   ###
list   = ['castigate','brave','prowess','tenacious','pre-emptive','orthodox','arcane','corpuscle','putrid','infidel','stratagem','affinity','abnegate','infraction']
mean   = ['to scold','courageous','skill','stubborn','early','traditional','mysterious','a living cell','rotting','unbeliever','scheme','attraction','to renounce','violation of law']
list1 = list.copy()

mean1 = mean.copy()
mean2 = mean.copy()
mean3 = mean.copy()
mean4 = mean.copy()

from random import randint
import random

word_count = len(list) - 1
options = []

options = random.sample(range(1, word_count), 4)

options1 = options.copy()
options2 = options.copy()
options3 = options.copy()
options4 = options.copy()
opt1 = options1.pop(0)
opt2 = options2.pop(1)
opt3 = options3.pop(2)
opt4 = options4.pop(3)

x = randint(0,3)
y = options.pop(x)
#ignore [options]
question = list.pop(y)
answer = mean.pop(y)

print("What is the meaning of",question,"?")
print("1)",mean1.pop(opt1))
print("2)",mean2.pop(opt2))
print("3)",mean3.pop(opt3))
print("4)",mean4.pop(opt4))

while True:
    try:
        userans = int(input("\nYour answer: "))
    except ValueError:
        print("Sorry, I didn't get that.")
        continue
    else:
        break

if userans - 1 is x:
    print("Your answer is correct!")
else:
    if userans is 100:
        print("There are %s words in your personal dictionary" % word_count)
    else:
        if userans > 4:
            print("It's OK if you do not know the answer. Better luck next time:)\nThe meaning of %s is %s!" % (question, answer))
        else:
            print("Your answer is wrong!\nThe meaning of %s is %s!" % (question, answer))

基本上,这段代码包含两个包含单词和含义的主要列表。

于 2019-06-03T09:09:05.350 回答
0

问题

您的主要问题是您在测验文件中存储/检索事物的方式。

你正在做f.write(str(entry)),这是写条目的字符串表示。我不太确定你的意图是什么,但你应该意识到两件事:1)str列表的表示很难转回列表(在读取文件时)和 2)write()最后不附加换行符。如果你要这样做:

f.write("line1")
f.write("line2")
f.write("line3")

然后您的文件将如下所示:

line1line2line3

无论如何,所有内容都保存在一行上,所以当你这样做时f.readlines(),它会返回一个像这样的对象:

["['alpha', 'bravo']['one', 'two']['x', 'y']"]

或更一般地说:

[a_string,]

如您所见,它是一个列表,其中只有一项。这就是为什么你在做的时候会出错

if (answer == text[1]):   

您正在尝试访问不存在的第二个项目。

解决方案?

您需要做的是将每个测验/答案对存储为单独的行,并使用特定的分隔符分隔测验和答案:

    quiz, answer
    alpha, bravo
    one, two
    etc...

例如:

with open("myquizfile.txt", "w") as f:
    while keepGoing: #You'd have to add your own exit logic.
        question = input("Enter a question: ")
        answer = input("Enter an answer: ")
        f.write("{0},{1}\n".format(question, answer)) #Notice the newline, \n

要读取此文件,您需要执行以下操作:

with open("myquizfile.txt", "r") as f:
    question_answer_pairs = [line.split(",") for line in f]
于 2012-08-18T22:53:13.547 回答
0

如果有人对该程序感兴趣,这是我的最终代码(再次感谢 Joel Cornett 的帮助):

#!/usr/bin/python3.2
# -*-coding:Utf-8 -*

#Vocabulary/translation quiz

import os
import random

keep_adding=input("Would you like to add a new word ? If yes, press \"O\" : ")
with open("data.txt","a") as f:
    while keep_adding=="O":
        word=input("Enter a word : ")
        translation=input("And its translation : ") 
        f.write("{0},{1},\n".format(word,translation))
        keep_adding=input("To continue, press \"O\" : ")


#in case the file doesn't exist, we create one :
with open("data.txt","a") as f:
    pass

os.system('clear')
print("* * * QUIZ STARTS ! * * *")

with open("data.txt","r") as f:
    question = [line.split(",") for line in f]
    i = 0
    score = 0
    while i<len(question):
        num = random.randint(0,len(question)-1)
        print("\nQuestion number ",i+1,": \nWhat is the translation for ", question[num][0], "?")
        answer = input("Answer : ")
        if (answer == str(question[num][1])):
            print("Congratulations ! That's the good answer !")
            score += 1
        else:
            print("Wrong. The correct answer was : ",question[num][1])
        i += 1

if len(question)==0:
    print("\nThe file is empty. Please add new words to start the quiz !\n")
else:   
    if i>1:
        qu_pl = "questions"
    else:
        qu_pl = "question"
    if score>1:
        sc_pl = "answers"
    else:
        sc_pl = "answer"
    print("\n RESULTS :\n ",i, qu_pl,", ",score,"correct ",sc_pl," \n"\
    ," --> Your score is : ",score*100/i,"% !\n")
于 2012-08-19T11:07:36.847 回答