Skip to content

Instantly share code, notes, and snippets.

/tagging.clj Secret

Created March 15, 2013 15:19
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 anonymous/6cdd57718f14454bbe46 to your computer and use it in GitHub Desktop.
Save anonymous/6cdd57718f14454bbe46 to your computer and use it in GitHub Desktop.
tagging
(def tag-tree
{:ships {:destroyers #"(?i)(destroyer|burke(-| )class)"
:minesweepers #"(?i)avenger(-| )class"
:lcs #"(?i)(littoral|\bLCS\b)"}
:marines #"\b(Marine(|s| Corps))\b"
:aviation {:aircraft #"(?i)\b(jet(|s))\b"
:aviators #"(?i)\b(aviator(|s))\b"}
:bases {:air-stations #"(?i)(naval air station)"
:whidbey-island #"(?i)whidbey island"}
:pacific {:asia {:korea #"(?i)\bkorea(|n)\b"}
:hawaii #"Hawaii"}})
(defn re?
[x]
(isa? (class x) java.util.regex.Pattern))
(defn tag
"Returns a set of tags from the given tag map. The tag map should be
a map from tag values to either regexes or other nested tag
maps. Tags bubble up, so that the deepest matching tag inherits all
of the tags above it."
[text tag-map]
(set
(mapcat (fn [[t test]]
(cond
(re? test) (when (re-seq test text) (list t))
(map? test) (when-let [result (tag text test)]
(when (not (empty? result))
(cons t result)))))
tag-map)))
;; example
;; (tag "Marine Corps aviators fly jets in Hawaii" tag-tree)
;; #{:aircraft :hawaii :pacific :aviators :aviation :marines}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment