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