Created
September 26, 2011 06:04
-
-
Save cataska/1241694 to your computer and use it in GitHub Desktop.
Get currency from web
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
(ns cataska | |
(:use clojure.contrib.str-utils) | |
(:import (java.net URL) | |
(java.io BufferedReader InputStreamReader))) | |
(def coin | |
["TWD" "CNY" "JPY" "KRW" | |
"HKD" "THB" "SGD" "IDR" | |
"VND" "MYR" "PHP" "INR" | |
"AED" "KWD" "AUD" "NZD" | |
"USD" "CAD" "BRL" "MXN" | |
"ARS" "CLP" "VEB" "EUR" | |
"GBP" "RUB" "CHF" "SEK" | |
"ZAR"]) | |
(def calias {"NTD" "TWD", "RMB" "CNY"}) | |
(def coins (str (str-join "|" coin) "|" (str-join "|" (keys calias)))) | |
(defn incase-pattern [s] | |
(. java.util.regex.Pattern (compile s java.util.regex.Pattern/CASE_INSENSITIVE))) | |
(defn expand-alias [alias] | |
(if (calias alias) | |
(calias alias) | |
alias)) | |
(defn make-url [money from to] | |
(str "http://tw.money.yahoo.com/currency_exc_result?amt=" money | |
"&from=" from | |
"&to=" to)) | |
(defn fetch-url [address] | |
(with-open [stream (.openStream (URL. address))] | |
(let [buf (BufferedReader. (InputStreamReader. stream))] | |
(apply str (line-seq buf))))) | |
(defn extract-input2 [input] | |
(let [r (incase-pattern (format "^([\\d\\.\\+\\-\\*\\/]+)\\s*(%s)\\s+to\\s+(%s)$" coins coins)) | |
matcher (re-matcher r input)] | |
(if (.matches matcher) | |
{:money (. matcher group 1) | |
:from (expand-alias (.. matcher (group 2) toUpperCase)) | |
:to (expand-alias (.. matcher (group 3) toUpperCase))}))) | |
(defn extract-input [input] | |
(let [r (incase-pattern (format "^([\\d\\.\\+\\-\\*\\/]+)\\s*(%s)$" coins)) | |
matcher (re-matcher r input)] | |
(if (.matches matcher) | |
{:money (. matcher group 1) | |
:from (expand-alias (.. matcher (group 2) toUpperCase)) | |
:to "TWD"} | |
(extract-input2 input)))) | |
(defn get-currency [s] | |
(let [res (fetch-url (make-url (:money s) (:from s) (:to s))) | |
r (re-pattern "經過計算後, (.+?)<div") | |
matcher (re-matcher r res)] | |
(if (.find matcher) | |
(re-gsub #"</?em>" "" (. matcher group 1)) | |
"抱歉"))) | |
(defn currency | |
"Get currency from web" | |
[text] | |
(let [m (extract-input text)] | |
(if m | |
(get-currency m) | |
"抱歉"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment