bibtex-rubyを使って、Mendeleyでエクスポートしたbibファイルをcsv形式にする。
環境
Rubyの環境構築はRVMで行っている。(Ruby 2.1.0 + Ruby on Rails 4.0.2)
% rvm -v rvm 1.25.22 (stable) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/] % ruby -v ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-linux]
ソースコード
以下の内容をbib2csv.rbとする。
# -*- coding: utf-8 -*-
require 'bibtex'
require 'csv'
class BibTeXToCSV
def initialize(bibfile)
unless File.exist?(bibfile)
puts "error: no such file #{bibfile}\n"
exit
end
@bib = BibTeX.open(ARGV[0])
@attributeAry = Array.new
@bib.each do | ref |
ref.to_hash.each_key do |key|
@attributeAry.push(key) unless @attributeAry.include?(key)
end
end
@attributeAry.sort!
end
def to_csv(output)
puts " Transform bib to ary ...\n"
# 見出し行の作成
bibAry = Array.new
tmpAry = ["id"] + @attributeAry
bibAry.push(tmpAry)
# 各書誌情報を配列に。存在しない属性はN/Aで統一
index = 1
@bib.each do | ref |
refHash = ref.to_hash
tmpAry = Array.new
tmpAry.push(index)
index += 1
@attributeAry.each do | attribute |
if refHash.key?(attribute)
# 余計な中括弧の除去
if refHash[attribute] =~ /^\{(.*)\}$/
str = $1
else
str = refHash[attribute]
end
tmpAry.push(str)
else
tmpAry.push('N/A')
end
end
bibAry.push(tmpAry)
end
# CSVとして書き出し
puts " Create csv file #{output}"
CSV.open(output, "wb") do | csv |
bibAry.each do | ary |
csv << ary
end
end
end
end
begin
if ARGV.length != 2
puts "error: please input path to the target bib file and output file.\n"
exit
end
b = BibTeXToCSV.new(ARGV[0])
b.to_csv(ARGV[1])
rescue => ex
puts ex.message
puts $@
end
使い方
Mendeleydeskdopで出力したbibファイルを my.bibとしたとき以下のように使う。
% ruby bib2csv.rb my.bib my.csv