PYTHON:尝试创建词汇/翻译测验(初级)

时间:2012-08-18 22:15:23

标签: python

我是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时,正确使用它。

3 个答案:

答案 0 :(得分: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))

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

答案 1 :(得分: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]

答案 2 :(得分: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")