python中文本文件的数字排序

2024-10-04 01:23:53 发布

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

我尝试按编号顺序对文本文件进行排序(首先显示最高值),每个值都在新行上。下面是我存储在.txt文件中的数据示例,每次用户完成测验时都会写入该文件。你知道吗

'Anton v1'0 'Antonv2'0 'Henry'0 'Joe'0 'Berty'0 'Lee'0 'Antttton'1 'Anton22'0

到目前为止,我已经找到了如何按字母顺序排列它们,这解决了我的部分问题:

with open('class1.txt', 'r') as r:
    for line in sorted(r):
        print(line, end='')

Tags: 文件数据用户txt示例排序顺序line
2条回答

试试这个:

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='')

下面是一个如何使用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

相关问题 更多 >