分页: 1 / 1

终端查词典的ruby脚本

发表于 : 2010-12-25 23:03
xiao2004

代码: 全选

#code=utf-8
# Author: hhuai
# Email: 8863824@gmail.com
# worked on: ubuntu 10.10 + rubymine3.0.1

require 'net/http'
require 'uri'
require 'rexml/document'

include REXML


class ConsoleDict
  def initialize(word)
    @word = word    
  end

  def get_content
    Net::HTTP.get URI.parse('http://dict.cn/ws.php?utf8=true&q='+@word)
  end

  def parser(xml)
    h = {"sent" => []}
    document = Document.new xml
    document.root.each_element do |element|
      value = nil
      if element.name.eql? "sent"
        sent_h = {}
        element.each do |dd|
          sent_h[dd.name] = dd.text
        end
        h[element.name] << sent_h
      else
        h[element.name] = element.text
      end
    end
    h
  end
end

if ARGV.length != 1
  puts "usage: "+File.basename(__FILE__)+" word"
  exit
end
console_dict =  ConsoleDict.new(ARGV[0])
xml = console_dict.get_content
#puts xml
begin
h = console_dict.parser xml
puts h["key"] + " [" + h["pron"] + "]"
puts h["def"]
puts "-"*70

if h["sent"] and h["sent"].is_a? Array
  h["sent"].each do |sent|
    puts sent["orig"].gsub(/<(\/)?em>/,'')
    puts sent["trans"]
  end
end

unless File.exist?("/usr/bin/mpg123")
  puts "if you want play audio, must be install mpg123, like sudo apt-get install mpg123."
end

mp3_path = "/tmp/"+h["key"]+".mp3"

#change you tool, if you want.
command = "wget -q --no-cookies -O "+mp3_path +" "+h["audio"]+" && mpg123 -q "+mp3_path
system(command)
rescue Exception=>e
	puts xml
	puts e.getmessage
end

2010.12.26
更新一下,发现一个没有解释时,程序会异常的问题。
将发音工具用mpg123来代替好了,moc难用。


例:

代码: 全选

$ ruby ./lib/console_dict.rb  exclude
exclude [ik'sklu:d]
vt.排除, 阻止, 拒绝接受 
----------------------------------------------------------------------
No one was excluded from sentry duty.
人人都得站岗放哨。
We cannot exclude the possibility that he killed his wife.
我们不能排除他杀了他妻子的可能性。

Re: 终端查词典的ruby脚本

发表于 : 2010-12-25 23:16
photor
:em11 :em11 :em11

Re: 终端查词典的ruby脚本

发表于 : 2010-12-25 23:54
eexpress
咋这么长。
播放mp3,直接用play就是