hamadata's diary

エンジニアのブログ

ハッカーと画家をKindleで読む。(Hackers and Painters by Paul Graham)

Web業界では有名なエッセイスト兼プログラマーのポール・グレアムの本は、Kindle versionを11ドルいくらかで買えるが、そのほとんど(全部?)は、著者のページにアップロードされている。

KindleにはWebブラウザが内蔵されているので、著者のWebサイトをブックマークすればいつでも見られるはずだが、my Kindleは3Gがついてないプロレタリアート仕様なので、Wi-Fi接続できない場所では見ることができない。

Amazon.comが提供している"kindlegen"ってプログラム(htmlファイルをつっこむとなんかうまい具合に処理してくれる)とRubyのスクリプトでごにょごにょやれば、Kindleで読める.mobiファイルに変換できることが分かったので、ここに公開しておく。

超やっつけ仕事なので、だれか添削してください(>_<)

require 'rubygems'
require 'hpricot'
require 'open-uri'

#read the link of essays
htmllist = Hpricot(open("http://www.paulgraham.com/articles.html"))
hash = Hash.new

(htmllist/:a).each do |link|
	hash.store(link[:href] ,link.inner_html)
end


hash.delete_if {|href, title| href =~ /.*index\.html.*/}
hash.delete_if {|href, title| href =~ /.*\.txt/}

hash.each do |href, title|
	puts title
	doc = Hpricot(open("http://www.paulgraham.com/#{href}"))
        (doc/'img').remove
	newhtml = "<html>  <head><title>#{title} </title> </head><body>#{(doc/:td)[3]}</body> </html>"
	File.open(href, 'w'){|f|
		f.write(newhtml)
	}
	system ("kindlegen #{href}")
end