【发布时间】: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,很多东西对我来说都是新的,我不知道什么是对的,什么不是?
【问题讨论】:
-
您可以将所需输出行的示例添加到输入行吗?
-
请看上面