我正在尝试按编号顺序对文本文件进行排序(首先显示最高值),每个值都在一个新行上。以下是存储在.txt文件中的数据示例,每次用户完成测验时都会写入该文件。
' Anton v1' 0' Antonv2' 0' 0' Joe' 0' Berty' 0& #39; Lee' 0' Antttton' 1 ' Anton22' 0
到目前为止,我已经找到了如何按字母顺序排序,这解决了我的部分问题:
with open('class1.txt', 'r') as r:
for line in sorted(r):
print(line, end='')
答案 0 :(得分:0)
试试这个:
from __future__ import absolute_import
import re
import operator
def to_number(s):
try:
return int(re.sub(r'^\s*(\d+)[^0-9].*$', r'\1', s))
except ValueError:
return 10**10
data = []
with open('class1.txt', 'r') as r:
for line in r:
data.append((to_number(line), line))
for x in sorted(data, key=operator.itemgetter(0)):
print(x[1], end='')
答案 1 :(得分:0)
以下是如何使用csv
模块以及如何使用自定义键对数据进行排序的示例。
首先,有几个实用功能:
import csv
def read_csv(filename, row_formats=None, **csvopts):
"""
Read from a Comma Separated Value file;
returns a list of rows, where each row is a list of cell-values
"""
with open(filename, newline='') as csvfile:
rd = csv.reader(csvfile, **csvopts)
if row_formats:
data = [[fmt(cell) for fmt,cell in zip(row_formats, row)] for row in rd]
else:
data = list(rd)
return data
def write_csv(filename, data, **csvopts):
"""
Write to a Comma Separated Value file;
`data` is an iterable of rows, where each row is an iterable of cell values
"""
with open(filename, 'w', newline='') as csvfile:
wt = csv.writer(csvfile, **csvopts)
wt.writerows(data)
现在,我们可以加载您的数据文件
data = read_csv("class3.txt", (str, int))
给了我们
data = [
['Anton v1', 0],
['Antonv2', 0],
['Henry', 0],
['Joe', 0],
['Berty', 0],
['Lee', 0],
['Antttton', 1],
['Anton22', 0]
]
排序,
def sort_key(row):
"""
This will sort by descending score then by ascending name
"""
return -row[1], row[0]
data.sort(key=sort_key)
导致
data = [
['Antttton', 1],
['Anton v1', 0],
['Anton22', 0],
['Antonv2', 0],
['Berty', 0],
['Henry', 0],
['Joe', 0],
['Lee', 0]
]
你可以把它写回文件,如
write_csv("class3.txt", data)
生产时
Antttton,1
Anton v1,0
Anton22,0
Antonv2,0
Berty,0
Henry,0
Joe,0
Lee,0