Skip to content

Instantly share code, notes, and snippets.

@AlexLynd
Last active September 24, 2021 13:13
Show Gist options
  • Save AlexLynd/617eda6ec3827b1788f1692c3343d715 to your computer and use it in GitHub Desktop.
Save AlexLynd/617eda6ec3827b1788f1692c3343d715 to your computer and use it in GitHub Desktop.
Python script to parse a calendar text file to json
months = ["January","February","March","April","May","June","July","August","September","October","November","December"]
from datetime import date, timedelta
import re
c = open("calendar.txt", "r")
text = c.read()
c.close()
days = [day[0] for day in re.findall(r"(([A-Z]{1,3}[a-z]{0,3}[0-9]|Off|Sp))", "".join(str(x) for x in [sch[0] for sch in re.findall(r"(([A-Z]{1,3}[a-z]{0,3}[0-9]|Off|Sp){15}|([A-Z]{1,3}[a-z]{0,3}[0-9]|Off|Sp){5})", text)]))]
span = [datespan[0] for datespan in re.findall(r"((August|September|October|November|December|January|February|March|April|May) [0-9]{1,2}-[0-9]{1,2}|(August|September|October|November|December|January|February|March|April|May) [0-9]{1,2}-(August|September|October|November|December|January|February|March|April|May) [0-9]{1,2})",text)]
dates = []
for rrange in span:
if any(x in rrange for x in months[7:]): cyear = 2020
else: cyear = 2021
if re.compile(r"[0-9]{1,2}-[0-9]{1,2}").search(rrange): # month #-#
sdate = date(int(cyear),months.index(rrange.split(" ")[0])+1,int(rrange.split(" ")[1].split("-")[0]))
edate = date(int(cyear),months.index(rrange.split(" ")[0])+1,int(rrange.split(" ")[1].split("-")[1]))
else:
sdate = date(int(cyear),months.index(rrange.split(" ")[0])+1,int(rrange.split(" ")[1].split("-")[0]))
edate = date(int(cyear),months.index(rrange.split(" ")[1].split("-")[1])+1,int(rrange.split(" ")[2]))
delta = edate - sdate
for i in range(delta.days + 1): dates.append(sdate + timedelta(days=i))
cjson = open("calendar.json", "w")
cjson.write("{\n")
for i in range (0,len(dates)):
cjson.write("\""+str(dates[i])+"\""+":"+"\""+days[i])
if (i==len(dates)-1): cjson.write("\"\n")
else: cjson.write("\",\n")
cjson.write("}")
cjson.close()
@AlexLynd
Copy link
Author

This doesn't really work but it kinda does

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment