Skip to content

Instantly share code, notes, and snippets.

/tagging.clj Secret
Created Mar 15, 2013

Embed
What would you like to do?
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
You can’t perform that action at this time.