2017-11-09 10 views
0

나는 궁금한 파이썬 문제가 있습니다.달 단위로 월 단위로 정렬하기 대신

스크립트는 두 개의 csv 파일을 사용합니다. 하나는 날짜 열이고 다른 하나는 텍스트 스 니펫 열입니다. 다른 파일에는 여러 개의 이름 (하위 문자열)이 있습니다. 코드가 수행하는 모든 작업은 두 달의 이름 매트릭스를 작성하는 두 목록을 단계별로 수행합니다. 날짜와 텍스트

  • FILE : (날짜, 발췌문 첫 번째 열)
  • ENTRY 1 : 2014 등 11월 일 (21), 아이폰 (7)의 방출을했다 ...

- 문자열 파일

  • 아이폰 7

  • 개 사과

  • 사과

  • 혁신 등

문제는 그 난 열이 asceding 순서 예에 따라 있도록 주문하려고 할 때 옥트 2014 년 11 월 2014 년 12 월 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')) 

을 보았다 그러나 나는 나를 위해 일하는 것이 있는지 확실하지 않다? 나의 이해에서 나는 내가 단지 파이썬과 많은 것을 배우고 시작, 먼저 주문 데이터 누락

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

같이하고, 날짜 12 ~ 13을 구문 분석 내가 옳은 일을 잘 모릅니다 나에게 새로운 및 뭐라구?

What is outputted 내가 원하는 무엇 (올바르게 정렬 된 데이터와 물론) : 당신이 CSV 파일을 읽고 찾아 태그를 계산에 대해 너무 많은 관련이없는 물건을했기 때문에 Ordered by increasing month-year (data of course sorted along with the dates)

+0

입력 행에 원하는 출력 행의 예를 추가 할 수 있습니까? – Nf4r

+0

위를 참조하십시오. –

답변

0

이 잠시했다. 그러나 당신은 이미 모든 것을 가지고 있으며, 사람들을 혼란스럽게하는 것을 피하기 위해 질문에서 완전히 배제되었을 것입니다.

실제 질문은 "날짜를 어떻게 정렬합니까?"

물론 "Apr-16"이 "Oct-14"앞에 오면 학교에서 알파벳을 가르쳐주지 않았습니까? A가 첫 글자입니다! 나는 요점을 강조하는 것이 바보 스럽다. 단순한 문자열이 아니고 날짜가 아니기 때문이다.

이미 발견했듯이 문자열을 datetime 클래스 메서드 strptime이있는 날짜로 변환해야합니다. 클래스는 모듈과 이름이 같기 때문에 가져 오는 방법에주의를 기울여야합니다. 그런 다음 나중에 실제 datetime (또는 date) 인스턴스에서 멤버 메서드 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) 

[ '10 월 14', '12 월 15 일', '4 월 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', '12 월 -15 ', '4 월 -16']

관련 문제