【问题标题】:Sort by date and string in python在python中按日期和字符串排序
【发布时间】:2014-03-17 23:59:06
【问题描述】:

我有一堆文件名为

公司名称-日期_somenumber.txt

我必须根据公司名称对文件进行排序,然后根据日期对文件进行排序,并将其内容按此排序顺序复制到另一个文本文件中。

这是我正在尝试的方法:

从每个文件名中,提取公司名称和日期,将这两个字段放入字典中,将该字典附加到一个列表中,然后根据公司名称和日期这两列对这个列表进行排序。

然后一旦我有了排序顺序,我想我可以根据我刚刚获得的文件顺序搜索文件夹中的文件,然后将每个文件内容复制到一个txt文件中,我将得到我的最终txt文件.

这是我到目前为止的代码:

myfiles = [ f for f in listdir(path) if isfile(join(path,f)) ]
file_list=[]

for file1 in myfiles:

    # find indices of companyname and date in the file-name
    idx1=file1.index('-',0)
    idx2=file1.index('_',idx1)
    company=file1[0:idx1]  # extract companyname
    thisdate=file1[idx1+1:idx2]  #extract date, which is in format MMDDYY
    dict={}
    # extract month, date and year from thisdate 
    m=thisdate[0:2]
    d=thisdate[2:4]
    y='20'+thisdate[4:6]
    # convert into date object
    mydate = date(int(y), int(m), int(d))
    dict['date']=mydate
    dict['company']=company
    file_list.append(dict)  

我在这段代码的末尾检查了 file_list 的输出,我想我有我的字典列表。现在,我如何按公司名称然后按日期排序?我在网上查找了按多个键排序,但我如何获得按日期递增的顺序?

有没有其他方法可以按字符串和日期字段对列表进行排序?

【问题讨论】:

  • 哈哈,这就是YY-MM-DD 的日期格式非常有用的原因。您的文件已经按正确的顺序排列了。
  • 你是对的。我会尝试以这种方式重命名它们。谢谢

标签: python sorting dictionary text-files


【解决方案1】:
import os
from datetime import datetime

MY_DIR = 'somedirectory'

# my_files = [ f for f in os.listdir(MY_DIR) if os.path.isfile(os.path.join(MY_DIR,f)) ]
my_files = [
    'ABC-031814_01.txt',
    'ABC-031214_02.txt',
    'DEF-010114_03.txt'
]
file_list = []

for file_name in my_files:
    company,_,rhs = file_name.partition('-')
    datestr,_,rhs = rhs.partition('_')
    file_date = datetime.strptime(datestr,'%m%d%y')
    file_list.append(dict(file_date=file_date,file_name=file_name,company=company))

for row in sorted(file_list,key=lambda x: (x.get('company'),x.get('file_date'))):
    print row

函数sorted 采用关键字参数key,这是一个应用于您正在排序的序列中的每个项目的函数。如果此函数返回一个元组,则序列将按元组中的项依次排序。

这里lambda x: (x.get('company'),x.get('file_date')) 允许sorted 按公司名称然后按日期排序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2016-08-07
    • 2022-01-19
    相关资源
    最近更新 更多