简体   繁体   中英

How do I get each line from a text file and split it so that I can use them all separately in python

This is my text file

I want to strip each line of the text file so in python it prints as:

1) The question

a) Option1

b) Option2

C) Option3

In my text file after the question the first option is the correct answer. I want to randomize this so that the correct answer is not the first option. After the user has answered one question it moves on to the next. Every time they get the question correct they get 1 point.

Here is my code so far but I do not understand what to do further:

    with open("ComputerScience.txt","r") as f:
    for line in f:
        y = line.split(",")
        print(y)

My problem with this is that it splits each lines and just turns each line into a list and outputs it. Thank you and please tell me if you need more info on this.

You can use random.shuffle() for changing the order of the array. The options are shuffled every time you run the code. Calculated score accordingly.

import random
with open('text.txt','r') as f:
    score=0
    x=((f.readlines()))
    f.seek(0)
    for i in range(len(x)):

        line=(f.readline().split(','))
        line[-1]=line[-1][:-1]
        print(line[0])
        options=line[1:]
        random.shuffle(options)
        for x,y in enumerate(options,0):
            print('{} ) {}'.format((x),y))
        answer=int(input('enter option number :\n'))
        if line[1]==options[answer]:
            score +=1
    print("END OF TEST")

print("\nThe total score obtained is {}".format(score))

1) what's binary?
0 )  addition
1 )  sums
2 )  1's and 0's
3 )  base 10
enter option number :
2
2) what does RAM stand for?
0 )  Random access memory
1 )  Read area memory
2 ) readable access memory
3 )  random area memory
enter option number :
0
3) what does cpu stand for?
0 )  central proccessing unit
1 )  control proccessing unit
2 )  control purpose unit
3 )  central protocol unit
enter option number :
0
END OF TEST

The total score obtained is 3

check the positions of options when I run second time.

1) what's binary?
0 )  1's and 0's
1 )  sums
2 )  addition
3 )  base 10
enter option number :
0
2) what does RAM stand for?
0 ) readable access memory
1 )  Random access memory
2 )  random area memory
3 )  Read area memory
enter option number :
1
3) what does cpu stand for?
0 )  control proccessing unit
1 )  central protocol unit
2 )  central proccessing unit
3 )  control purpose unit
enter option number :
2
END OF TEST

The total score obtained is 3

3rd output when not all answer are correct check the score.

1) what's binary?
0 )  base 10
1 )  sums
2 )  addition
3 )  1's and 0's
enter option number :
3
2) what does RAM stand for?
0 )  Read area memory
1 ) readable access memory
2 )  random area memory
3 )  Random access memory
enter option number :
1
3) what does cpu stand for?
0 )  central protocol unit
1 )  central proccessing unit
2 )  control proccessing unit
3 )  control purpose unit
enter option number :
0
END OF TEST

The total score obtained is 1

Calculates scores according to the student's inputted options. if you want your option to start from 1 then use :

for x,y in enumerate(options,1):
            print('{} ) {}'.format(x,y))

the logic for calculating the score is :

if line[1]==options[answer-1]:
            score +=1

output would be like this

1) what's binary?
1 )  1's and 0's
2 )  sums
3 )  base 10
4 )  addition

If you want your options to start from 'a' then you this code below

for x,y in enumerate(options,ord('a')):
            print('{} ) {}'.format(chr(x),y))

the logic for calculating the score is :

if line[1]==options[ord('a')-ord(answer)]:
            score +=1

Output would be like this :

1) what's binary?
a )  sums
b )  base 10
c )  addition
d )  1's and 0's

Hope this helps you.

use striplines() to read all the lines from a open file object

q,a,b,c,d ='','','','',''

def schema(q,a,b,c,d):


    n,s = q.split(')')[0], ''.join(q.split(')')[1:])
    return  {'question': {
            'number':n,
            'statement':s
            },
           'options': {'a': a,
                       'b':b,
                       'c':c,
                       'd':d

                   }}

t =[]

with open("/home/prashant/COmputerScience.txt", 'r') as f:
    for line in f.readlines():
        if line.strip():
            q,a,b,c,d = line.strip().split(',')
            t.append(schema(q,a,b,c,d))

print(t)

output

 [
  {'question': {
          'number': '1',
          'statement': ' What is Binary?'
          }, 
    'options': {
            'a': " 1's and 0's", 
            'b': ' Base 10', 
            'c': ' Sums', 
            'd': ' Addition'
            }
    }, 
    {'question': {
            'number': '2',
            'statement': ' What does RAM stand for?'
            },
    'options': {
            'a': ' Random Access Memory', 
            'b': ' Read Area Memory',
            'c': ' Redable Access Memory',
            'd': ' Random Area Memory'
            }
    },
    {'question': {
            'number': '3',
            'statement': ' What does CPU stand for?'
            },
    'options': {
            'a': ' Central Processing Unit',
            'b': ' COntrol Processing Unit',
            'c': ' Central Protocol UNit',
            'd': ' Control Purpose Unit'
            }
    }
]    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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