Python按字段对文本文件进行排序

标签 python class sorting text-files

我在按特定字段对文本文件中的数据进行排序时遇到了一些问题。以后可能会通过多个字段。 .txt 是几千行代码。我是 python 的新手,所以我的代码可能有点乱。例如,这是我将从中读取的文本文件:

stuff
123 1200 id-aaaa stuart@test.com
322 1812 id-wwww machine-switch@test.com
839 1750 id-wwww gary2-da@test.com
500 0545 id-aaaa abc123@test.com
525 1322 id-bbbb zyx321@test.com

我的代码如下:

filelist = open("info.txt").readlines()
splitlist = list()

class data:
    def __init__(self, eventName, time, identity, domain):
        self.evenName = eventName
        self.time = time
        self.identity = identity
        self.domain = domain

for line in filelist:
    filelist = list.split(', ')
    splitlist.append(filelist)

for column in splitlist:
    if (len(column) > 1): #to skip the first line
        eventName = column[0].strip()
        time = column[1].strip()
        identity = column[2].strip()
        domain = column[3].strip()

我想按身份对 .txt 文件逐行排序,然后按时间排序。我看到这可以通过 python 教程中的类来完成,所以我正在尝试走那条路。请指教。谢谢!

最佳答案

with open("info.txt") as inf:
    data = []
    for line in inf:
        line = line.split()
        if len(line)==4:
            data.append(line)

data.sort(key=lambda s:(s[2],s[1]))

如果你想变得更高级一些,

from collections import namedtuple
Input = namedtuple('Input', ('name', 'time', 'identity', 'domain'))

with open("info.txt") as inf:
    inf.next()  # skip header
    data = [Input(*(line.split()) for line in inf]

data.sort(key=lambda s:(s['identity'],s['time']))

如果您真的非常想使用一个类,请尝试:

import time

class Data(object):
    def __init__(self, event, time_, identity, domain):
        self.event = event
        self.time = time.strptime(time_, "%H%M")
        self.identity = identity
        self.domain = domain

with open("info.txt") as inf:
    data = []
    for line in inf:
        try:
            data.append(Data(*(line.split()))
        except TypeError:
            # wrong number of arguments (ie header or footer)
            pass

data.sort(key=lambda s:(s.identity,s.time))

关于Python按字段对文本文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972925/

相关文章:

sorting - 如果按字母顺序排序,则查找字符串最大值和最小值的公式

python - 解决 Sympy 中的不平等

python - 如何从图像中去除外部空心轮廓而不影响内部轮廓

python - 基本 Python 类

python - 'int' 对象在 lambda python 中不可下标

asp.net - GridView排序: SortDirection always Ascending

python - 在Python中使用get Total函数

python - Selenium 的最佳测试量

C++ 指针和类

c++ - 从 QString 到 Class 类型