Skip to content

Instantly share code, notes, and snippets.

@kristenmills
Forked from kurtraschke/parsecallno.py
Last active December 22, 2015 20:09
Show Gist options
  • Save kristenmills/6524419 to your computer and use it in GitHub Desktop.
Save kristenmills/6524419 to your computer and use it in GitHub Desktop.
Some scripts to work with library of congress call numbers. Eventually to be used in some fashion in Alexandria.
#Connects to the library of congress database.
#Given a ISBN, it fetches the LCC.
require 'zoom'
require 'marc'
require 'stringio'
ZOOM::Connection.open('z3950.loc.gov', 7090) do |conn|
conn.database_name = 'VOYAGER'
conn.preferred_record_syntax = 'USMARC'
while true
print '>> '
STDOUT.flush
i = gets.chomp
puts i
conn.search("@attr 1=7 #{i}").each_record do |item|
MARC::Reader.new(StringIO.new(item.raw)).each do |rec|
puts rec['245']['a']
puts "#{rec['050']['a']} #{rec['050']['b']}"
end
end
end
end
# Given a list of Libary of congress call numbers,
# normalizes and sorts them properly.
myfile = File.open('list')
callnos = Array.new
myfile.each do |line|
callnos << line.chomp
end
@p = /^(?<aclass>[A-Z]{1,3})(?<nclass>\d{1,4})(\ ?)(\.(?<dclass>\d{1,3}))?(?<date>\ [A-Za-z0-9]{1,4}\ )?([\ \.](?<c1>[A-Z][0-9]{1,4}))(\ (?<c1d>[A-Za-z0-9]{0,4}))?(\.?(?<c2>[A-Z][0-9]{1,4}))?(\ (?<e8>\w*)\ ?)?(\ (?<e9>\w*)\ ?)?(\ (?<e10>\w*)\ ?)?/
def ncmp x, y
if x.nil? and y.nil?
return 0
elsif x.nil?
return -1
elsif y.nil?
return 1
end
x = x.to_i
y = y.to_i
x <=> y
end
def cmp x, y
x <=> y
end
def sortfunc x, y
xp = @p.match(x)
yp = @p.match(y)
parts = {
aclass: :cmp,
nclass: :ncmp,
dclass: :ncmp,
date: :cmp,
c1: :cmp,
c1d: :cmp,
c2: :cmp,
e8: :cmp,
e9: :cmp,
e10: :cmp
}
parts.each do |part_key, part_value|
cr = send(part_value, xp[part_key], yp[part_key])
if cr != 0
return cr
end
end
end
def normalize callno
cp = @p.match(callno)
out = cp[:aclass] + cp[:nclass]
if not cp[:dclass].nil?
out += ".#{cp[:dclass]}"
end
if not cp[:date].nil?
out += " #{cp[:dclass]} "
end
out += ".#{cp[:c1]}"
if not cp[:c1d].nil?
out += " #{cp[:c1d]} "
end
if not cp[:c2].nil?
out += " #{cp[:c2]}"
end
if not cp[:e8].nil?
out += " #{cp[:e8]}"
end
if not cp[:e9].nil?
out += " #{cp[:e9]}"
end
if not cp[:e10].nil?
out += " #{cp[:e10]}"
end
out
end
callnos.sort!{|a,b| sortfunc(a, b)}
callnos.each do |callno|
printf "%25s %25s\n", callno.chomp, normalize(callno).chomp
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment