Skip to content

Instantly share code, notes, and snippets.

@gitcrtn
Last active September 28, 2015 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gitcrtn/21508b433d73174aab73 to your computer and use it in GitHub Desktop.
Save gitcrtn/21508b433d73174aab73 to your computer and use it in GitHub Desktop.
docomoのvcsファイル(vCalenderフォーマット)によるメモ帳データをtxtファイルにコンバートします
# -*- coding: shift-jis -*-
# vcs converter
# 2015.09.23
# @Carotene
# -d : save directory path of the output text file
# -i : input vcs file path
from argparse import ArgumentParser
import os, os.path, datetime, quopri
def timestamp():
return datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
class tz_custom(datetime.tzinfo):
def __init__(self,hours,minutes):
super(datetime.tzinfo, self).__init__()
self.hours = hours
self.minutes = minutes
def utcoffset(self,dt):
return datetime.timedelta(hours=self.hours,minutes=self.minutes)
def dst(self,dt):
return datetime.timedelta(0)
def tzname(self,dt):
return 'CustomZone'
def parse_quopri(file_pointer,buf_prefix):
buf = buf_prefix
line = file_pointer.readline()
while line:
if (line == '\n') or (':' in line):
break
else:
buf += line
line = file_pointer.readline()
return quopri.decodestring(buf.replace('=\n=','=').replace('\n','')), line
def main():
parser = ArgumentParser()
parser.add_argument("-d", "--directory", dest="savedir", help="save directory", type=str)
parser.add_argument("-i", "--input", dest="input_file", help="input vcs file", type=str)
args = parser.parse_args()
if os.path.splitext(args.input_file)[1] != '.vcs':
print 'Error: Input file is not vcs.'
return
if not os.path.isdir(args.savedir):
print 'Error: Save directory does not exist.'
return
if not os.path.isfile(args.input_file):
print 'Error: Input vcs file does not exist.'
return
f = open(args.input_file,'r')
line = f.readline()
if line.startswith('BEGIN:VCALENDAR'):
line = f.readline()
if line.startswith('VERSION:'): line = f.readline()
else:
print 'Error: Input file is not vcs format.'
return
in_event = False
event_instance = None
events = []
while line:
if line.startswith('BEGIN:VEVENT'):
in_event = True
event_instance = dict()
elif line.startswith('END:VEVENT'):
in_event = False
event_instance['date'] = event_instance['date'].replace(tzinfo=event_instance['timezone'])
events.append(event_instance)
event_instance = None
elif line.startswith('TZ:'): event_instance['timezone'] = tz_custom(hours=int(line[3:6]),minutes=int(line[7:9]))
elif line.startswith('DESCRIPTION;CHARSET=SHIFT_JIS;ENCODING=QUOTED-PRINTABLE:'):
event_instance['content'], line = parse_quopri(f,line[len('DESCRIPTION;CHARSET=SHIFT_JIS;ENCODING=QUOTED-PRINTABLE:'):])
continue
elif line.startswith('SUMMARY;CHARSET=SHIFT_JIS;ENCODING=QUOTED-PRINTABLE:'):
event_instance['title'], line = parse_quopri(f,line[len('SUMMARY;CHARSET=SHIFT_JIS;ENCODING=QUOTED-PRINTABLE:'):])
continue
elif line.startswith('LAST-MODIFIED:'):
event_instance['date'] = datetime.datetime.strptime(line.strip()[len('LAST-MODIFIED:'):],'%Y%m%dT%H%M%SZ')
line = f.readline()
f.close()
with open('%s/vcs_%s_%s.txt' % (args.savedir.replace('\\','/'),os.path.splitext(os.path.basename(args.input_file))[0],timestamp()),'w') as f:
events.sort(key=lambda x:x['date'],reverse=True)
for e in events:
f.write('[%s]\n\n' % e['date'].strftime('%Y/%m/%d %H:%M:%S'))
f.write('Title: %s\n\n' % e['title'])
f.write('%s\n\n' % e.get('content',''))
f.write('=' * 30 + '\n\n')
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment