python排序问题,给出一个txt文件,怎样按分数高低进行排序?

2024-08-15 06:11:48
推荐回答(4个)
回答1:

把你每条数据的格式发出来看下。
不然不好弄。

其实就是通过正则表达式等方神誉燃式,把分数提取出来,然后排序就行了。

给你两个函数,你自己组合吧

#构建一个列表,filename是你txt文件的路径,构建的列表,按照分数进行排序并返回,参数reverse为False则为升序,为True则为降序

def build_list(filename):
import re

reslist = []

fp = open(filename)
textlist = fp.readlines()
fp.close()

pattern = re.compile("(\\d*)\\.\\s*(\\d*\\.\\d*)\\s*([\\s\\S]*(?=\\(\虚察\d*\\)))\\((\\d*)\\)\\s*([\\w,]*)")

for text in textlist:
pr = pattern.search(text)
if pr:
reslist.append((pr.group(1),pr.group(2),pr.group(3),pr.group(4),pr.group(5)))

reslist.sort(key = lambda x:float(x[1]))
return reslist

#根据输入的year参数,返回year年度的电影资料的列表,year为字符串,movielist为使用上面的build_list函数生成的列表
def list_movie_by_year(movielist,year):
return [x for x in movielist if x[3] == year]

如,你数据的路径为d:\data.txt

sorted_list = build_list('d:/data.txt')

想找1993年的游虚数据,
则调用函数
list_movie_by_year(sorted_list,'1993')

回答2:

比如你的备缺文件叫做film.txt吧。
import re
time="1994" #查询的年份
for i in open("film.txt","r"):
if re.search("(%s)"%time,i):
print i

#前提是圆贺年份都是(1985)这种样子,如果括仿腔辩号不一定有的话,把括号去掉估计也行

回答3:

竟然有人在知道问作业。。。不知道这题是老师自己出的么。。。

回答4:

import string
import math

file=open('橡核top250.txt','r')

file.readline()
file.readline()

order=range(250)
for i in order:
s=file.readline()
k=s.split()
order[i]=k

year=int(raw_input('please input a year'))

total=0

for m in order:
str_year=m[len(m)-2]
s_year=int(str_year[1:5])
if year==s_year:
total=total+1

i=0
indexing=range(total)
for m in order:
str_year=m[len(m)-2]
s_year=int(str_year[1:5])
if year==s_year:
indexing[i]=m
i=i+1

i=0
while total>梁铅掘0:
m=0
while m if indexing[m][2]>indexing[m+1][2]:
s=indexing[m]
indexing[m]=indexing[m+1]
indexing[m+1]=s
m=m+1
total=total-1

def letter(list,pop):
letter=list[pop][2]
return letter[0]

def fen(list0,pop0):
st=list0[pop0][1]
return float(st)

i=0
while i<400:
x=0
while x<激搭len(indexing)-1:
if letter(indexing,x)==letter(indexing,x+1):
if fen(indexing,x) y=indexing[x]
indexing[x]=indexing[x+1]
indexing[x+1]=y
x=x+1
i=i+1

def vott(list1,pop1):
s=list1[pop1][-1]
e=string.split(s,',')
return int(e[0])*1000+int(e[1])

w=0
while w<300:
x=0
while x if letter(indexing,x)==letter(indexing,x+1):
if math.fabs(fen(indexing,x)-fen(indexing,x+1))<10**(-2):
if vott(indexing,x) g=indexing[x]
indexing[x]=indexing[x+1]
indexing[x+1]=g
x=x+1
w=w+1

i=0
while i o=indexing[i]
string1=string.join(o)
print string1
i=i+1