我有一个奇怪的python问题。在
该脚本接受两个csv文件,一个包含日期列,另一个包含文本片段列。在另一个excel文件中有一组名称(子字符串)。
代码所做的只是逐步检查两个列表,建立一个每月提到的名字矩阵。在包含日期和文本的文件:(日期,代码段第一列)
条目1:2014年11月21日星期日等等,iPhone7的发布是。。。在
-字符串文件iphone 7
苹果
苹果
创新等
问题是,当我试图按升序排序时,比如2014年10月、2014年11月、2014年12月等等,它只是将月份组合在一起,这不是我想要的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...')
据我所知我是月。排序()没有做我期望的事?
我已经看了这里,他们使用attrgetter应用其他函数对数据进行排序
^{pr2}$
然后呢sorted(l, key=attrgetter('month'))
但我不确定这是否对我有用?
根据我的理解,我分析了日期12-13,我是不是先错过了订单数据data = sorted(data, key = lambda row: datetime.strptime(row[0], "%b-%y"))
我才刚刚开始学习python,很多东西对我来说都是新的,我不知道什么是对的,什么是不对的?在
我想要的(当然是正确排序的数据):