Hi! I’m clsung

Hi! I’m clsung

clsung’s blog site, or you can call me AlanSung

Hi! I’m clsung RSS Feed
 
 
 
 

[ruby] 第一支 ruby 程式

寫 paper 寫到快瘋掉時,就會想做點奇怪的事。

早上翻到 Tsung 的文章,有 sed/perl 寫的 Y! dictionary script,然後手也癢了起來。用 python 寫嗎?可是感覺失去挑戰性了,畢竟已經是初學者的身份了,拿這個寫就沒有學習的快樂了。所以就挑上 ruby 啦,反正也是照著彥明的 script 直翻,大概就像這樣啦:

完整的程式在這裡。唔,因為 ports 裡沒有 term-ansicolor,所以我也順手送上去了。

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 =~ /<em class="warning">/
        if html =~ /<em class="warning">.*?>(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 class=p(w+)>(.*?)</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 /<b>/, bold
        line = line.gsub /</b>/, $reset
        line = line.gsub /<[^>]+>/, $reset
        print $color , line + "n" , reset
    end
    puts ""
end

ydict(ARGV[0])

看起來好像可以再簡化(比如說 “+=” 或 “.=” 這東西不知道有沒有相對應的),不過第一個 ruby 程式就不用太講究啦。 :)

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • funp
  • Haohao
  • Hemidemi
  • Live
  • MisterWong
  • TwitThis
  • udn

Leave a Reply

噗浪:

  • clsung 已經 買了上週發現的好吃快炒店的炒麵。 6 hours 前
  • clsung 說 原來老師已經回來了。 11 hours 前
  • clsung 說 為了怕在家裡洗頭到一半瓦斯沒了,今天一定要來去游泳 *握拳* 11 hours 前

分類

Flickr

    clsung. Get yours at bighugelabs.com/flickr

Blogroll

    馬的警總回來了
Creative Commons Attribution-NonCommercial-ShareAlike 2.5 Taiwan
Creative Commons Attribution-NonCommercial-ShareAlike 2.5 Taiwan