简体   繁体   English

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

[英]PYTHON: Trying to create a vocabulary/translation quiz (Beginner)

I'm new to Python (and also to stackoverflow, as you will easily notice it !) 我是Python的新手(也是stackoverflow的新手,您会很容易注意到它!)

I'm actually trying to write a program that would work as follow : the user launch the program. 我实际上是在尝试编写一个可以按如下方式工作的程序:用户启动该程序。 he's being asked whether he wants to enter a new word, and the translation of that word. 有人问他是否要输入一个新单词,以及该单词的翻译。 The word and its translation are stored in a file (data.txt). 单词及其翻译存储在文件(data.txt)中。 When he's done adding new words, the quiz starts. 完成添加新单词后,测验开始。 The program pick a word, and ask the user for the translation. 该程序选择一个单词,并要求用户进行翻译。 If the answer is similar to the translation in the file, the program returns "Great !", if not, it prints the correct answer. 如果答案与文件中的译文相似,则程序返回“ Great!”,否则返回正确的答案。

As you can see, it's pretty simple. 如您所见,这非常简单。 My problem here is working with the file, especially retrieving what is inside the file and using it correctly. 我的问题是使用文件,尤其是检索文件内部内容并正确使用它。

Here is my code : 这是我的代码:

#!/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])

Thanks a lot for your help ! 非常感谢你的帮助 !

EDIT : did bring some corrections to my code. 编辑:确实给我的代码带来了一些更正。 What I get is the following : 我得到的是以下内容:

    * * * 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

and in my file, I have this : 在我的文件中,我有这个:

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

So actually, I would like to get only the first word in the question (ie alpha) and when answering bravo, having it right. 因此,实际上,我只想得到问题中的第一个单词(即alpha),并且在回答bravo时正确。

You can alternatively do this; 您可以选择执行此操作; this requires no external files:) 这不需要外部文件:)

###   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))

Basically, this code contains two main lists containing words and meanings. 基本上,此代码包含两个主要列表,其中包含单词和含义。

The problem 问题

You're main issue is the way you're storing/retrieving things in the quiz file. 您的主要问题是在测验文件中存储/检索内容的方式。

You're doing f.write(str(entry)) , which is writing the string representation of the entry. 您正在执行f.write(str(entry)) ,它正在编写条目的字符串表示形式。 I'm not quite sure what your intent is here, but you should realize two things: 1) str representations of lists are tricky to turn back into lists (when reading the file) and 2) write() doesn't append newlines at the end. 我不太确定您的意图是什么,但您应该意识到两件事:1)列表的str表示很难转换回列表(在读取文件时),并且2) write()不会在以下位置添加换行符结束。 If you were to do: 如果要这样做:

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

Then your file would look like this: 然后您的文件将如下所示:

line1line2line3

Anyway, everything is saved on one line, so when you do f.readlines() , this returns an object like so: 无论如何,所有内容都保存在一行中,因此当您执行f.readlines() ,这将返回一个对象,如下所示:

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

Or more generally: 或更笼统地说:

[a_string,]

As you can see, it's a list with only one item in it. 如您所见,它是一个列表,其中仅包含一项。 That's why you get an error when you do 这就是为什么当您这样做时会出错

if (answer == text[1]):   

You're trying to access a second item that doesn't exist. 您正在尝试访问不存在的第二项。

The solution? 解决方案?

What you need to do is store each quiz/answer pair as a separate line, with a specific delimiter separating the quiz and answer: 您需要做的是将每个测验/答案对存储在单独的行中,并使用特定的分隔符将测验和答案分开:

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

For example: 例如:

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

And to read this file, you'd do something like this: 要读取此文件,您需要执行以下操作:

with open("myquizfile.txt", "r") as f:
    question_answer_pairs = [line.split(",") for line in f]

In case someone would be interested in the program, here is my final code (and thanks again Joel Cornett for your help) : 如果有人对该程序感兴趣,这是我的最终代码(再次感谢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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM