Created
May 28, 2011 21:42
-
-
Save xuwei-k/997262 to your computer and use it in GitHub Desktop.
2.9.0Dynamic使って、ScalaのREPLを辞書として使う
This file contains hidden or 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
// 1 -Xexperimentalのオプションつけて、2.9.0のScala REPL を立ち上げ | |
// 2 上記のコードのキーの部分だけgoogleさんから取得したものに書き換えて、コピペ | |
scala> Translate | |
res0: Translate.type = Translate$@766d65fd | |
// ScalaのREPLでは、レシーバーの名前省略して、"."から始めると、前回の式で評価されたオブジェクトをレシーバーにしてのメソッド呼び出しになる。 | |
// そして、applyDynamicで自身を返しているので、 | |
// .翻訳したい単語 | |
// という形式で、何度でも繰り返し呼び出せる | |
scala> .hello | |
dynatype: $line1.$read.$iw.$iw.res2.applyDynamic("hello")() | |
List(Hi, こんにちは, hello) | |
// 英単語で、スペース区切りで複数の単語、というか熟語調べられるように、ちょっと変更した | |
// :silent モードにしたほうが、よけいなもの表示されなくてオヌヌメ(・ω・´) | |
This file contains hidden or 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
object Translate extends Dynamic{ | |
import scala.util.parsing.json.JSON | |
type ReturnJsonType = Map[String,Map[String,List[Map[String,String]]]] | |
private val url = "https://www.googleapis.com/language/translate/v2?" + | |
"key=自分のキー&source=" + | |
( _:String ) + "&target=" + (_:String) + "&q=" + java.net.URLEncoder.encode( _:String,"UTF-8") | |
val urlJa = url("ja","en",_:String) | |
val urlEn = url("en","ja",_:String) | |
val alpha = "([\\p{Alpha}\\s]+)" r | |
def applyDynamic(q:String)(args:Any * ):this.type = { | |
@annotation.tailrec | |
def loop(result:List[String],n:Int):List[String] = { | |
if( n < 0 ) result | |
else{ | |
val u = result.head match { | |
case alpha(en) => urlEn(en) //アルファベットのみなら、英語 => 日本語に翻訳 | |
case ja => urlJa(ja) // それ以外は、日本語 => 英語 | |
} | |
val json = JSON.parseFull( io.Source.fromURL(u,"UTF-8").mkString ).get.asInstanceOf[ReturnJsonType] | |
// println(json) | |
loop(json("data")("translations")(0)("translatedText") :: result , n - 1) | |
} | |
} | |
// 何回ループするかの判断。デフォルトだと 日本語 => 英語 => 日本語 というように、一度翻訳したものを、逆に翻訳するようになってる | |
val count = if(args.length > 0 && args(0).isInstanceOf[Int]) args(0).asInstanceOf[Int] else 1 | |
val r = loop(List(q),count) | |
history += r | |
println(r) | |
this | |
} | |
//熟語の場合に普通に呼べない(´・ω・`) | |
//で、その場合 .applyDinamic("as if")() って呼んでも呼べるけど | |
//それを .m("as if") っていう感じで、できるだけ短く呼ぶためのやつ | |
def m(query: String ):this.type = applyDynamic(query)() | |
val history = collection.mutable.ArrayBuffer[List[String]]() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment