This commit is contained in:
Daniel Tsvetkov 2019-04-20 23:23:30 +02:00
parent fae628b534
commit 17ca8f8b33
2 changed files with 17 additions and 16 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
venv venv
data/.cache.csv data/.cache.csv
__pycache__ __pycache__
.idea

32
tww.py
View File

@ -3,10 +3,9 @@
Find time now, in the past or future in any timezone or location. Find time now, in the past or future in any timezone or location.
""" """
import os
import argparse import argparse
import logging import logging
import sys import os
import dateparser import dateparser
from pytz.exceptions import UnknownTimeZoneError from pytz.exceptions import UnknownTimeZoneError
@ -20,6 +19,7 @@ basepath = os.path.dirname(os.path.abspath(__file__))
logging.basicConfig() logging.basicConfig()
logger = logging.getLogger() logger = logging.getLogger()
def parse_args(): def parse_args():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('query', nargs='*', default="now", help="<datetime-like> to <timezone-like or location string>") parser.add_argument('query', nargs='*', default="now", help="<datetime-like> to <timezone-like or location string>")
@ -36,19 +36,19 @@ def setup_logging_level(debug=False):
logger.debug("Debugging enabled") logger.debug("Debugging enabled")
class Location: class Location:
""" """
Represents a location with name, latitude and longitude Represents a location with name, latitude and longitude
""" """
def __init__(self, name:str, latitude: float, longitude: float):
def __init__(self, name: str, latitude: float, longitude: float):
self.name = name self.name = name
self.latitude = latitude self.latitude = latitude
self.longitude = longitude self.longitude = longitude
def __lt__(self, other): def __lt__(self, other):
return self.name < other.name return self.name < other.name
def __str__(self): def __str__(self):
return "{} {} {}".format(self.name, self.latitude, self.longitude) return "{} {} {}".format(self.name, self.latitude, self.longitude)
@ -59,9 +59,9 @@ def normalize_words_to_number(query):
Assumes one-word numbers used Assumes one-word numbers used
""" """
from word2number import w2n from word2number import w2n
normal_list = [] normal_list = []
for word in query.split(): for word in query.split():
try: try:
normal_list.append(str(w2n.word_to_num(word))) normal_list.append(str(w2n.word_to_num(word)))
@ -79,7 +79,7 @@ def timezone_to_normal(query):
america/new_york -> America/New_York america/new_york -> America/New_York
""" """
import re import re
# The magic in the regex is that it splits by either / OR _ OR - # The magic in the regex is that it splits by either / OR _ OR -
# where the | are OR; and then the parens ( ) keep the splitting # where the | are OR; and then the parens ( ) keep the splitting
# entries in the list so that we can join later # entries in the list so that we can join later
@ -98,9 +98,9 @@ def create_if_not_exists(fname):
def write_to_cache(query, location): def write_to_cache(query, location):
import csv import csv
logger.debug("Writing location to cache") logger.debug("Writing location to cache")
with open(os.path.join(basepath, "data",".cache.csv"), 'a+') as wf: with open(os.path.join(basepath, "data", ".cache.csv"), 'a+') as wf:
cachewriter = csv.writer(wf) cachewriter = csv.writer(wf)
cachewriter.writerow([query, cachewriter.writerow([query,
location.latitude, location.latitude,
@ -124,11 +124,11 @@ def resolve_location_local(query):
from fuzzywuzzy import fuzz from fuzzywuzzy import fuzz
query = query.lower() query = query.lower()
create_if_not_exists(os.path.join(basepath, "data",".cache.csv")) create_if_not_exists(os.path.join(basepath, "data", ".cache.csv"))
# location hypothesis heap # location hypothesis heap
heap = [] heap = []
for fname in [".cache", "countries", "cities"]: for fname in [".cache", "countries", "cities"]:
with open(os.path.join(basepath, "data", "{}.csv".format(fname))) as f: with open(os.path.join(basepath, "data", "{}.csv".format(fname))) as f:
cfile = csv.reader(f) cfile = csv.reader(f)
@ -196,9 +196,9 @@ def parse_query(query):
logger.debug("raw human_dt: {}".format(human_dt)) logger.debug("raw human_dt: {}".format(human_dt))
logger.debug("raw human_tz_loc: {}".format(human_tz_loc)) logger.debug("raw human_tz_loc: {}".format(human_tz_loc))
human_dt = normalize_words_to_number(human_dt) human_dt = normalize_words_to_number(human_dt)
return human_dt, human_tz_loc return human_dt, human_tz_loc