如何从文本文件中获取每一行并将其拆分,以便在python中分别使用它们

2024-04-23 16:18:47 发布

您现在位置:Python中文网/ 问答频道 /正文

This is my text file

我想剥离文本文件的每一行,以便在python中打印为:

1)问题

a)选项1

b)选项2

C)选项3

在我的文本文件后的问题,第一个选项是正确的答案。我想随机化,这样正确的答案就不是第一个选择了。 在用户回答了一个问题之后,它会转到下一个问题。他们每答对一题就得1分。你知道吗

这是我目前的代码,但我不知道该怎么做:

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

我的问题是,它将每一行拆分,然后将每一行转换成一个列表并输出。 谢谢你,如果你需要更多的信息请告诉我。你知道吗


Tags: 答案代码text用户txtismy选项
2条回答

使用striplines()读取打开的文件对象中的所有行

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)

输出

 [
  {'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'
            }
    }
]    

可以使用random.shuffle()更改数组的顺序。每次运行代码时,选项都会被洗牌。据此计算得分。你知道吗

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

第二次运行时检查选项的位置。你知道吗

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

第三次输出不是所有答案都正确时检查分数。你知道吗

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

根据学生输入的选项计算分数。 如果希望选项从1开始,请使用:

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

计算分数的逻辑是:

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

输出是这样的

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

如果您希望您的选项从'a'开始,那么您可以使用下面的代码

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

计算分数的逻辑是:

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

输出如下:

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

希望这对你有帮助。你知道吗

相关问题 更多 >