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']

したがって、実際には、質問の最初の単語 (つまりアルファ) だけを取得し、ブラボーに答えるときにそれを正しくしたいと考えています。

4

3 に答える 3

0

問題

あなたの主な問題は、クイズファイルに物を保存/取得する方法です。

f.write(str(entry))これは、エントリの文字列表現を書いています。ここであなたの意図が何であるかはよくわかりませんが、2つのことを理解する必要があります.1)strリストの表現は(ファイルを読み取るときに)リストに戻すのが難しいです.2)write()最後に改行を追加しません。あなたがするなら:

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

次に、ファイルは次のようになります。

line1line2line3

とにかく、すべてが 1 行に保存されるため、 を実行するとf.readlines()、次のようなオブジェクトが返されます。

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

またはより一般的に:

[a_string,]

ご覧のとおり、これは項目が 1 つしかないリストです。そのため、実行するとエラーが発生します

if (answer == text[1]):   

存在しない 2 番目のアイテムにアクセスしようとしています。

ソリューション?

あなたがする必要があるのは、クイズと回答を区切る特定の区切り文字を使用して、各クイズ/回答のペアを個別の行として保存することです。

    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 に答える