我的第一个Ruby程序:调用金山词霸在线API查询单词
Wed May 20 2009
Migarated from here at ‘2012-06-04 17:16:25’.
使用”金山词霸查词接口beta版”实现了在线查询单词功能,以下是代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 require 'open-uri' require 'rexml/document' require 'cgi' include REXML class Ciba def initialize (word ) @word = word end def search open("http://dict-co.iciba.com/api/dictionary.php?w=" + CGI : :escape (@word )) do |http | @result = http.read end end def parse doc = Document .new(@result ) doc.elements.each("dict/key" ) { |e | puts e.text } doc.elements.each("dict/ps" ) { |e | puts "[" + e.text + "]" } pos_array = Array .new() doc.elements.each("dict/pos" ) { |e | pos_array.push(e.text) } acc_array = Array .new() doc.elements.each("dict/acceptation" ) { |e | acc_array.push(e.text) } pos_array.each_index { |i | puts pos_array[i] + " " + acc_array[i] } pos_array.clear doc.elements.each("dict/sent/orig" ) { |e | pos_array.push(e.text) } acc_array.clear doc.elements.each("dict/sent/trans" ) { |e | acc_array.push(e.text) } pos_array.each_index { |i | puts "例句" + (i+1 ).to_s + ":" + pos_array[i] + " " + acc_array[i] } end end ciba = Ciba .new("cool" ) puts ciba.search 3 .times {puts "" }ciba.parse
以上程序的输出为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <?xml version="1.0" encoding="UTF-8" ?> <dict num ="219" id ="219" name ="219" > <key > cool</key > <ps > ku:l</ps > <pron > http://res.iciba.com/resource/amp3/b/1/b1f4f9a523e36fd969f4573e25af4540.mp3</pron > <pos > n.</pos > <acceptation > 凉爽, 凉爽的空气</acceptation > <pos > adj.</pos > <acceptation > 凉爽, 冷静的, 无所顾虑的, 淡漠的</acceptation > <pos > v.</pos > <acceptation > 使冷, 使镇定</acceptation > <sent > <orig > Cool.</orig > <pron > http://res.iciba.com/resource/phrase_mp3/6/3/63ebe9d367b10545dfd1c2cb7448c3e4.mp3</pron > <trans > 很好。</trans > </sent > <sent > <orig > That's cool!</orig > <pron > http://res.iciba.com/resource/phrase_mp3/8/c/8c6332d149db7bcc1498d0af543cc82b.mp3</pron > <trans > 好极了!</trans > </sent > <sent > <orig > Keep cool!</orig > <pron > http://res.iciba.com/resource/phrase_mp3/b/9/b98249b38337c5088bbc660d8f872d6a.mp3</pron > <trans > 保持冷静!别慌!</trans > </sent > <sent > <orig > Cool it.</orig > <pron > http://res.iciba.com/resource/phrase_mp3/e/6/e68dc4981c2310e883786e7f723fa37d.mp3</pron > <trans > 冷静下来,别那样兴奋。</trans > </sent > <sent > <orig > a cool autumn day; a cool room; cool summer dresses; cool drinks; a cool breeze.</orig > <pron > http://res.iciba.com/resource/phrase_mp3/a/f/af885e92d18e71365cfcbb9642c4ec60.mp3</pron > <trans > 凉爽的秋天;凉爽的房间;凉爽的夏装;凉爽的饮料;凉爽的微风。</trans > </sent > </dict >
1 2 3 4 5 6 7 8 9 10 cool [ku:l] n. 凉爽, 凉爽的空气 adj. 凉爽, 冷静的, 无所顾虑的, 淡漠的 v. 使冷, 使镇定 例句1:Cool. 很好。 例句2:That's cool! 好极了! 例句3:Keep cool! 保持冷静!别慌! 例句4:Cool it. 冷静下来,别那样兴奋。 例句5:a cool autumn day; a cool room; cool summer dresses; cool drinks; a cool breeze. 凉爽的秋天;凉爽的房间;凉爽的夏装;凉爽的饮料;凉爽的微风。