Created
November 1, 2011 03:37
-
-
Save paulkaplan/1329817 to your computer and use it in GitHub Desktop.
Hash features of a natural language time declaration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class String | |
def scan_first(pattern) | |
a = self.scan(pattern) | |
a = a.first while a.is_a? Array unless a.empty? | |
return a | |
end | |
end | |
time_tokens = {} | |
given = ARGV[0] | |
months = [ | |
"January", | |
"February", | |
"March", | |
"April", | |
"May", | |
"June", | |
"July", | |
"August", | |
"September", | |
"October", | |
"November", | |
"December" | |
] | |
regexps = { | |
:time => /\d?\d:\d\d/, | |
:meridian => /[AaPp][Mm]/, | |
:tomorrow => /tomorrow/, | |
:n_days_from_now => /(\d+) days from now/, | |
:in_n_days => /in (\d+) days/ | |
} | |
regexps.each do |k, v| | |
unless given.scan_first(v).empty? | |
time_tokens[k] = given.scan_first(v) | |
if given.scan_first(v) == 'tomorrow' then time_tokens[k] = 1 end | |
end | |
end | |
unless time_tokens[:tomorrow] or time_tokens[:n_days_from_now] or time_tokens[:in_n_days] | |
months.each do |m| | |
if given.include?(m) | |
time_tokens[:month] = m | |
unless given.scan_first(/#{m} (\d+)/).empty? | |
time_tokens[:day_of_month] = given.scan_first(/#{m} (\d+)/) | |
else raise "You must enter a date with a month" | |
end | |
end | |
end | |
else raise "You can't use a month with 'N days from now'" end | |
# Clean up a bit | |
[:n_days_from_now, :in_n_days].each do |x| | |
if time_tokens[x] | |
raise "Only use one 'n days' form" if time_tokens[:n_days] | |
time_tokens[:n_days] = time_tokens[x] | |
time_tokens.delete(x) | |
end | |
end | |
puts time_tokens |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment