【问题标题】:Sorting by month-year groups by month instead而是按月-年组按月排序
【发布时间】:2017-11-09 23:10:52
【问题描述】:

我有一个奇怪的 python 问题。

该脚本采用两个 csv 文件,一个包含一列日期,另一个包含一列文本 sn-ps。在另一个 excel 文件中有一堆名称(子字符串)。 代码所做的只是逐步遍历这两个列表,建立一个每月提及的名字矩阵。

  • 包含日期和文本的文件:(日期,片段第一列)
  • 条目 1:2014 年 11 月 21 日等,iphone 7 的发布是...

-字符串文件

  • iphone 7

  • 苹果

  • 苹果

  • 创新等

问题在于,当我尝试对其进行排序时,列会按照升序排列,例如oct-2014、nov-2014、dec-2014 等等,它只是将月份组合在一起,这不是我想要的

import csv
from datetime import datetime


file_1 = input('Enter first CSV name (one with the date and snippet): ')
file_2 = input('Enter second CSV name (one with the strings): ')
outp = input('Enter the output CSV name: ')


file_1_list = []
head = True
for row in csv.reader(open(file_1, encoding='utf-8', errors='ignore')):
    if head:
        head = False
        continue
    date = datetime.strptime(row[0].strip(), '%a %b %d %H:%M:%S %Z %Y')
    date_str = date.strftime('%b %Y')
    file_1_list.append([date_str, row[1].strip()])

file_2_dict = {}

for line in csv.reader(open(file_2, encoding='utf-8', errors='ignore')):
    s = line[0].strip()
    for d in file_1_list:
        if s.lower() in d[1].lower():
            if s in file_2_dict.keys():
                if d[0] in file_2_dict[s].keys():
                    file_2_dict[s][d[0]] += 1
                else:
                    file_2_dict[s][d[0]] = 1
            else:
                file_2_dict[s] = {
                    d[0]: 1
                }

months = []
for v in file_2_dict.values():
    for k in v.keys():
        if k not in months:
            months.append(k)
months.sort()

rows = [[''] + months]

for k in file_2_dict.keys():
    tmp = [k]
    for m in months:
        try:
            tmp.append(file_2_dict[k][m])
        except:
            tmp.append(0)
    rows.append(tmp)
print("still working on it be patient")
writer = csv.writer(open(outp, "w", encoding='utf-8', newline=''))
for r in rows:
    writer.writerow(r)

print('Done...')

据我了解,我是 months.sort() 没有做我期望的事情? 我看过这里,他们使用 attrgetter 应用其他一些函数对数据进行排序,

from operator import attrgetter

>>> l = [date(2014, 4, 11), date(2014, 4, 2), date(2014, 4, 3), date(2014, 4, 8)]

然后

sorted(l, key=attrgetter('month'))

但我不确定这是否适合我? 据我了解,我解析日期 12-13,我是否首先缺少订单数据,例如

data = sorted(data, key = lambda row: datetime.strptime(row[0], "%b-%y"))

我才刚刚开始学习python,很多东西对我来说都是新的,我不知道什么是对的,什么不是?

我想要的(当然是正确排序的数据):

【问题讨论】:

  • 您可以将所需输出行的示例添加到输入行吗?
  • 请看上面

标签: python sorting date text


【解决方案1】:

这需要一段时间,因为您有太多与读取 csv 文件以及查找和计数标签无关的内容。但是您已经掌握了所有这些,并且应该将其完全排除在问题之外以避免混淆人们。

看起来您的实际问题是“我如何对日期进行排序?”

当然“Apr-16”在“Oct-14”之前,他们不是在学校教过你字母吗? A是第一个字母!我只是愚蠢地强调一点——因为它们是简单的字符串,而不是日期。

正如您已经注意到的,您需要使用 datetime 类方法 strptime 将字符串转换为日期。因为类与模块同名,所以需要注意它是如何导入的。然后,您稍后使用实际日期时间(或日期)实例上的成员方法 strftime 返回字符串。

这是一个例子:

from datetime import datetime

unsorted_strings = ['Oct-14', 'Dec-15', 'Apr-16']
unsorted_dates = [datetime.strptime(value, '%b-%y') for value in unsorted_strings]
sorted_dates = sorted(unsorted_dates)
sorted_strings = [value.strftime('%b-%y') for value in sorted_dates]

print(sorted_strings)

['Oct-14', 'Dec-15', 'Apr-16']

或跳到最后

from datetime import datetime
unsorted_strings = ['Oct-14', 'Dec-15', 'Apr-16']
print (sorted(unsorted_strings, key = lambda x: datetime.strptime(x, '%b-%y')))

['Oct-14', 'Dec-15', 'Apr-16']

【讨论】:

    猜你喜欢
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    相关资源
    最近更新 更多