Skip to content

Instantly share code, notes, and snippets.

@penguin2716
Last active Sep 29, 2015
Embed
What would you like to do?
クリップボードにある文字列を英辞郎で検索してポップアップ通知で結果を表示してくれるプログラム.xbindkeys等でショートカットキーを設定すると良い.(MIT License)
#!/usr/bin/env ruby
require 'nokogiri'
require 'open-uri'
require 'clipboard'
require 'cgi'
require 'sqlite3'
dbname = File.join(ENV['HOME'], '.toast-alc.db')
table_name = 'query_result'
db = SQLite3::Database.new(dbname)
db.execute("create table #{table_name} (query text, result text);") if db.table_info(table_name).empty?
begin
query = Clipboard.paste
if query.nil?
db.close
exit
end
query_result = db.execute("select result from #{table_name} where query = '#{query}';")
result = nil
unless query_result.empty?
result = query_result.first.first
else
query_uri = "http://eow.alc.co.jp/search?q=#{CGI.escape(query)}"
html = open(query_uri).read
document = Nokogiri::HTML.parse(html)
summary = document.css('li').reject{|li| li.css('.wordclass').empty?}.first
summary.search('.tango').remove
summary.children[0..1].each(&:remove)
summary.children[-2..-1].each(&:remove)
summary.search('span.attr').remove
summary.search('.kana').each(&:remove)
summary.search('.ex_sentence').each(&:remove)
summary_html = summary.children.to_html
result = summary_html.gsub(/<[^>]*>/, '').gsub("\n\n", "\n").gsub(/^\n/, '')
db.execute("insert into #{table_name} values ('#{query}', '#{result}');")
end
`notify-send #{query} "#{result}"`
rescue => e
`notify-send -u critical error "#{e.backtrace}"`
end
db.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment