Python测验,需要指导

时间:2014-04-24 15:35:06

标签: python compare

这是我的第一个代码,所以如果你能忍受我并尽可能彻底。

此测验提出一个问题,并有4个可能的答案,您选择1-4。它读取的文件看起来像这样。正确答案显示在问题上方。

A
Which sport uses the term LOVE ?
A)Tennis
B)Golf
C)Football
D)Swimming
B
What is the German word for WATER ?
A)Wodar
B)Wasser
C)Werkip
D)Waski

我想要做的就是抓住这个大块而不回答它现在所做的问题,只回答问题和可能的答案。当你猜测它会将你的答案与真正的答案进行比较,看它是否匹配,如果是,你会得到一个分数,如果它没有,你就不会。我最大的疑问是如何比较它并在没有答案的情况下得到这些块。

quiz_file = '/home/wryther/Desktop/QUIZ.DAT'
num_questions = 146

def get_chunk(buf, n):

    while buf:
        chunk = [buf.readline() for _ in range(n)]

         if not any(chunk):
             chunk = None

         yield chunk

def get_awns(ans):  #This transfomrs the ints answers to str so it could compare if its right or wrong.
   if ans == 1:
         ans = 'A'
    elif ans == 2:
         ans = 'B'
    elif ans == 3:
         ans = 'C'
    elif ans == 4:
         ans = 'D'



with open(quiz_file) as quiz_contents:

    choices = [None] * num_questions

    i = 0

    for chunk in get_chunk(quiz_contents, 6):
            if not chunk:
            break

            print()
            for line in chunk:
            print(line)

            choices[i] = int(input("1   3\n2    4?\n:"))
            get_awns(choices[i])

我感谢所有回复,无论是批评,提示还是帮助,如果它与我的主题相关。

1 个答案:

答案 0 :(得分:0)

如果我正确地阅读了您的答案,那么您的问题是如何在每个块中将问题与答案分开。正如@jonrsharpe评论的那样,您必须分别访问每个块的项目。要么像jonrsharpe那样使用下标,要么你可以直接解压缩它们。

def readChunk(buf, n):
    for _ in range(n):
        yield next(buf).strip() #get rid of newlines

with open('questions.txt', 'r') as lines:
    while True:
        try:
            #Unpacking into separate values
            correct, question, *answers = readChunk(lines, 6)
        except ValueError:
            #End of file
            break
        print('The question is', question)
        print('And the answers are', answers)
        print('And the correct answers is', answers[ord(correct) - ord('A')])

使用您的示例文件,此代码段输出:

The question is Which sport uses the term LOVE ?
And the answers are ['A)Tennis', 'B)Golf', 'C)Football', 'D)Swimming']
And the correct answers is A)Tennis
The question is What is the German word for WATER ?
And the answers are ['A)Wodar', 'B)Wasser', 'C)Werkip', 'D)Waski']
And the correct answers is B)Wasser