Rubyで pdf から text 抽出してみる
ところが寝る前に HMDT3版を読んでいたら RubyCocoa*1 で pdf からの text 抽出が載っていた
ので、ちょっと Nature とかの pdf から text 抽出して doi を抜き出せるか試してみた。
#!/usr/bin/env ruby
#
# Created by mako on 2008-01-29.
# What?
# This_script.rb extracts text from pdf file
# 参考にした URL
# http://builder.japan.zdnet.com/sp/07leopard/story/0,3800082822,20360029-2,00.htm
begin
require 'osx/cocoa'
OSX.require_framework 'Quartz'
# window = OSX::NSWindow.alloc.initWithContentRect_styleMask_backing_defer([100, 100, 300, 300], 15, 2, 0)
# window.makeKeyAndOrderFront(nil)
# pdfview = OSX::PDFView.alloc.initWithFrame(window.contentView.frame)
# window.contentView.addSubview(pdfview)
pdf_files = ARGV
pdf_files.each do |pdf_file|
url = OSX::NSURL.fileURLWithPath("/Users/mako/#{pdf_file}")
pdfdocument = OSX::PDFDocument.alloc.initWithURL(url)
# pdfview.setDocument(pdfdocument)
content = pdfdocument.string unless pdfdocument == nil
puts ["#{pdf_file} => ", content.scan(/doi[\.|:].*/i)[0]].join("") unless content == nil
end
rescue Exception => e
p e.message
p e.backtrace
endRuby で抽出といつつ、どうみても RubyCocoa w
require_framework で Quartz してるのは、それに含まれる PDFKit を使いたいから。
PDFKit については HMDT3版の75ページ付近を参照にするといい。木下さんありがとう。
コメントアウトしてるのは、ここではウインドウを呼び出す必要がないから。
コメントアウトしない状態で Terminal 上にて実行すると
window.makeKeyAndOrderFront(nil)
でエラーになる("NSInternalInconsistencyException - Error (1002) creating CGSWindow")。
ここいら辺、 CocoaRepl だと勝手にやってくれているのかな?
まあ、Ruby でうまく Cocoa を使えると嬉しいね:-)

Happy Macintosh Developing Time Third Edition Cocoaプログラマのための技術解説書
- 作者: 木下誠
- 出版社/メーカー: ビー・エヌ・エヌ新社
- 発売日: 2006/05/25
- メディア: 単行本(ソフトカバー)
- クリック: 26回
- この商品を含むブログ (22件) を見る