繁体   English   中英

如何将文本文件中的文本放入列表并进行排序?

[英]How do I put text from a text file into a list and sort it?

测验应将分数和名称输入文本文件,然后可以选择从文本文件输出分数(从 最大到最小 )。 我需要一段代码,它将文件中的文本输出到列表中,然后让我对列表进行相应的排序

import os
import random

x = 0

while x <1:


    teacher = input("What is your class, choose from 'A', 'B' or 'C'? ").upper() 

    if teacher == 'A':
        if os.path.exists("classA.txt") == False: 
            myfile = open("classA.txt","w")
            myfile.close()
        x = x + 1 

    elif teacher == 'B':
        if os.path.exists("classB.txt") == False:
            myfile = open("classB.txt","w")
            myfile.close()
        x = x + 1

    elif teacher == 'C':
        if os.path.exists("classC.txt") == False:
            myfile = open("classC.txt","w")
            myfile.close()
        x = x + 1

    else:
        teacher != 'A' , 'B' , 'C' 
        print("Incorrect input, choose from 'A', 'B' or 'C' ")


score = 0
name = input("Please enter your name ")

for i in range (1,11):

    no1 = random.randint(0,11)
    no2 = random.randint(0,11)    
    question = random.randint(1,3)


    if question == 1:
        answer = no1 + no2
        guess = int(input("Question "+ str(i) + ") What is " + str(no1) + "+" + str(no2) + "= "))
        if guess == answer:
            score +=1
            print("That's the correct answer")
        else:
            print ("That's the incorrect answer")

    elif question == 2:
        answer = no1 * no2
        guess = int(input("Question "+ str(i) + ") What is " + str(no1) + "*" + str(no2) + "= "))
        if guess == answer:
            score +=1
            print("That's the correct answer")          
        else:
            print ("That's the incorrect answer")


    elif question == 3:
        answer = no1 - no2
        guess = int(input("Question "+ str(i) + ") What is " + str(no1) + "-" + str(no2) + "= "))
        if guess == answer:
            score +=1
            print("That's the correct answer")

        else:
            print ("That's the incorrect answer")

print ("Your score is " + str(score))



if teacher == 'A':
    classA = []
    classA.append([name , str(score)])
    classA = open("classA.txt","a")
    classA.write(name + str(score)+"\n")
    classA.close()


elif teacher == 'B':
    classB = []
    classB.append([name , str(score)])
    classB = open("classB.txt","a")
    classB.write(name + str(score)+"\n")
    classB.close()


elif teacher == 'C':
    classC = []
    classC.append([name ,  str(score)])
    classC = open("classC.txt","a")
    classC.write(name + str(score)+"\n")
    classC.close()

仅使用内置函数:

假设您的文本文件如下所示:

John 13
Jill 12
Juan 14
Phil 15
bill 16

您可以为此做些事情:

filen = open('filename.txt', 'r+')
filetxt = filen.read()
#filelist = []; filelist = filetxt.split(' ') #Splits by spaces
filelist = []; filelist = filetxt.split('\n')
#filelist = []; filelist = filetxt.split('') #Put whatever it should split by in the ('')
gradelist = []
for i in filelist:
    if i[-3:][:1] == '1': s = i[-3:]
    else: s = i[-2:]
    gradelist.append(s)
    gradelist.sort()
    b=0
    for x in gradelist:
        if x in i:
            gradelist[b] = i
        b=b+1
a=gradelist[0]
gradelist.remove(a)
gradelist.insert(len(gradelist), a)

print gradelist返回['Jill 12', 'John 13', 'Juan 14', 'Phil 15', 'bill 16']

我建议您在将分数输入文件时,使用定界符分隔分数和名称。 例如:classA.write(name +“-” + str(score)+“ \\ n”)

这段代码将执行Required:

import operator
f=open("classA.txt")
content={}
for line in f:
    content[line.strip().split("-")[0]]= line.strip().split("-")[1]
sorted_x = reversed(sorted(content.items(),     key=operator.itemgetter(1)))
for aTuple in sorted_x:
    print(aTuple[0] +" : "+aTuple[1])

使用列表itemgetter将内容读入列表列表。然后使用itemgetter进行sort

from operator import itemgetter

lines = [line.strip().split(' ') for line in open('results.txt')]

for each in lines:
    each[1] = int(each[1])
lines.sort(key=itemgetter(1))
print lines

要将文件中的文本输入到列表中,您需要使用“ r +”,以便您可以使用阅读行)

examplefile=open("filename.txt","r+")

然后,您可以使用“ readlines()”将文件的内容保存到列表中

listofcontents=examplefile.readlines()

文件的内容现在位于列表“ listofcontents”中,该列表由原始文本文件中的每一行分隔,您可以对其进行排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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