Python 按日期对行排序
所以我有一个包含一些行的.txt文件。。。 每行的格式如下:Python 按日期对行排序,python,python-3.x,sorting,datetime,Python,Python 3.x,Sorting,Datetime,所以我有一个包含一些行的.txt文件。。。 每行的格式如下:x(A-Z)creationDate completionDate Task+project@context(待办事项列表项目) 因此,我想按照它们的creationDate(第二种情况下是completionDate)对这些行进行排序,并将它们写入一个.txt文件中 例如: (D) 2018-03-02 2018-04-04 watch the new tomb raider +movie @tombraider (A) 20
x(A-Z)creationDate completionDate Task+project@context
(待办事项列表项目)
因此,我想按照它们的creationDate(第二种情况下是completionDate)对这些行进行排序,并将它们写入一个.txt文件中
例如:
(D) 2018-03-02 2018-04-04 watch the new tomb raider +movie @tombraider
(A) 2017-03-02 2017-03-10 say goodbye to your best friend!! +friendship @meetfriend
x (C) 2016-07-02 2016-08-05 finish gta vice city +gaming @playstation2
排序后:
x (C) 2016-07-02 2016-08-05 finish gta vice city +gaming @playstation2
(A) 2017-03-02 2017-03-10 say goodbye to your best friend!! +friendship @meetfriend
(D) 2018-03-02 2018-04-04 watch the new tomb raider +movie @tombraider
我该怎么做
感谢您花时间回答。使用sorted()
和lambda
with open(myfile, 'r') as f:
lines = [line.strip().split() for line in f]
sorted_lines = sorted(lines, key = lambda x: x[2])
这假设每行的
creationDate
位于位置2。然而,正如一条评论所指出的,是否有些行有x
前缀,而有些行没有前缀?如果没有,是否有字符(例如\s
或\t
)?那么每行的开头是否都有“x”?或者仅仅是(C)?到目前为止您尝试了什么?如果一行以“x”开头,那么它就是,否则它以空格开头。使用正则表达式提取日期,然后将其传递到datetime.strtime()
并对结果进行排序。仅此网站上就有几个帖子可以帮助您完成这些步骤。是的,它们要么以“x”开头,要么以“\s”开头