#!/usr/local/bin/ruby # Ruby version of Y! dictionary, derived from leeym's perl script # Author: Cheng-Lung Sung # Version: 0.9 # Date: 2007/01/12 require 'term/ansicolor' require 'net/http' require 'iconv' def ydict (shift) raise ArgumentError, 'Must specify word' if shift == nil include Term::ANSIColor Net::HTTP.start('tw.dictionary.yahoo.com', 80) {|http| response = http.get('/search?p=' + shift) @html = response.body } if ENV['LC_CTYPE'] =~ /Big5/ @html = Iconv.new('big5', 'utf-8').iconv(@html) end i = 0 html = @html.gsub /\r/, "" html = html.gsub /\n/, "" if html =~ // if html =~ /.*?>(\S+)<.*?<\/em>/ q = $1; print bold , yellow , "\nERROR: ", shift , " -> " , q , "\n", reset return ydict(q) else print bold , yellow , "ERROR: ", shift , "\n", reset return end end print bold , yellow , "\n" + shift + "\n" , reset while html =~ /
(.*?)<\/div>/i type = $1 line = $2 html = $' $reset = reset line = line.gsub /^\s+/, "" line = line.gsub /\s+$/, "" if type == 'cixin' i = 0 $color = bold, red elsif type == 'chi' or type == 'eng' $color = cyan; $reset = reset + $color line = "\t" + line elsif type == 'explain' i = i + 1 line = i.to_s + " " + line else color = bold, blue next end line = line.gsub //, bold line = line.gsub /<\/b>/, $reset line = line.gsub /<[^>]+>/, $reset print $color , line + "\n" , reset end puts "" end ydict(ARGV[0])