1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
|
# -*- coding: UTF-8 -*-
# -*- python -*-
# This file is part of pybliographer
#
# Copyright (C) 1998-2004 Frederic GOBRY
# Email : gobry@pybliographer.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#
# This script processes a text file with citations and creates a
# reference list according to the given style.
# Created by Zoltán Kóta. March, 2004.
'''Processing keys in a text file and appending a reference list'''
import string, os, re, copy, sys, getopt
from shutil import copyfile
from Pyblio import Base, Key, Autoload
from Pyblio.Style import Utils
from Pyblio import pybtextvar
import locale
charset = locale.getlocale () [1] or 'ascii'
def usage ():
print _("usage: pybtext [-o outputfile] [-s style] <textfile> <bibfiles...>").encode (charset)
return
def error (msg):
sys.stderr.write ((_("pybtext: error: %s\n") % msg).encode (charset))
sys.exit (1)
return
def warning (msg, exit = 0):
sys.stderr.write ((_("pybtext: warning: %s\n") % msg).encode (charset))
if exit:
sys.exit (1)
return
optlist, args = getopt.getopt (sys.argv [2:],
'o:s:',
['output=',
'style='])
# test input arguments
if len (args) < 2:
usage ()
sys.exit (1)
# set defaults if no option
outfile = args [0] + '.pyb'
style = 'Abbrev'
# get option values
for opt, value in optlist:
if opt == '-o' or opt == '--output':
outfile = value
continue
if opt == '-s' or opt == '--style':
style = value
continue
# get the specified style
url = None
style = os.path.splitext (style) [0]
if os.path.exists (style + '.xml'):
url = Fields.URL (style + '.xml')
else:
from Pyblio import version
full = os.path.join (version.pybdir, 'Styles', style)
full = full + '.xml'
if os.path.exists (full): url = Fields.URL (full)
if not url:
error (_("can't find style `%s'") % style)
spstyle = os.path.split (style) [1]
# adjust parameters to the chosen style
if spstyle == 'abbrvau':
sep = '; '
format = 'textau'
elif spstyle == 'abbrvnum':
sep = ', '
format = 'textnum'
else:
sep = ', '
format = 'text'
# get the specified output
output = Autoload.get_by_name ('output', format)
if output is None:
error (_("unknown output format `%s'") % format)
reffile = outfile + '.ref'
if os.path.exists(outfile):
error (_("File already exists: `%s'") % outfile)
if os.path.exists(reffile):
error (_("A file with the same name already exists: `%s'") % reffile)
textfile = args [0]
bibfile = args [1:]
# regular expression to match in the text file
citation_re = re.compile ('\[([^\]]+)\]')
# this function extracts the citation keys from the text file
def list_entries (file):
try:
txt = open (textfile, 'r')
except IOError, err:
error ("`%s': %s" % (textfile, str (err).decode (charset)))
citations = []
# parse the whole file
while 1:
line = txt.readline ()
if line == '': break
line = string.strip (line)
# we match new citations
match = citation_re.findall (line)
if match:
for citationkey in match:
# splitting multiple citations
ckeys = string.split (citationkey, ',')
for a in ckeys:
citations.append (a)
txt.close ()
return citations
# getting citation keys
entries = list_entries (textfile)
# is there something to do ?
if len (entries) == 0:
error (_("no citation found"))
# ensure citation keys unicity preserving citation order
h = []
for e in entries:
if h.count (e) >= 1:
continue
h.append (e)
entries = h
# storing citation order
order = copy.copy (entries)
sys.stderr.write ((_("pybtext: using style `%s', format `%s'\n") % (style, output.name)).encode (charset))
formatter = output.data
# we have to create a new database to hold the entries found in the
# given databases
r = Base.DataBase (None)
# use the bibliographic databases in order of declaration
# to solve the references
for bib in bibfile:
# open the database
db = bibopen (bib)
# as we are modifying the list of entries in this loop, we make a copy
# of it in order to avoid strange behaviors
orig = copy.copy (entries)
# loop over the expected entries
for e in orig:
# create a key in the current database
key = Key.Key (db, e)
# does the database provide the key ?
if db.has_key (key):
# yes, add it to the reference
r [key] = db [key]
# and remove it from the list
entries.remove (e)
# if we found some entries in the current database...
if len (r) > 0:
pass
# is it finished ?
if len (entries) == 0: break
# check if we were able to solve all the citations
if len (entries) > 0:
error (_("can't find the following entries: %s")
% string.join (entries, ", "))
# creating an ordered list of database keys to pass through
keys = map (lambda x: Key.Key (r, x), order)
# creating the reference list
try:
refs = open (reffile, 'w')
except IOError, err:
error (_("can't open `%s': %s") % (reffile, str (err).decode (charset)))
refs.write ("\n\nReferences:\n")
Utils.generate (url, formatter, r, keys, refs)
refs.close ()
# getting the old-new key pairs
oldnew = pybtextvar.oldnew
# Now we check the textfile again to replace bibdb keys
# to the new keys if it is needed
if oldnew:
try:
txt = open (textfile, 'r')
except IOError, err:
error ("`%s': %s" % (textfile, str (err).decode (charset)))
try:
dest = open (outfile, 'a')
except IOError, err:
error (_("can't open `%s': %s") % (outfile, str (err).decode (charset)))
citations = []
# parse the textfile
while 1:
line = txt.readline ()
if line == '': break
# we match a new citation
match = citation_re.findall (line)
if match:
for citationkey in match:
# splitting multiple citations
citations = string.split (citationkey, ',')
old = '[' + citationkey + ']'
new = ''
for a in citations:
new = new + oldnew.get (a) + sep
new = '[' + new [0:len (new) - 2] + ']'
out = line.replace (old, new, 1)
line = out
citations = []
dest.write (line)
txt.close ()
else:
try:
copyfile (textfile, outfile)
except:
error (_("can't create `%s'") % outfile)
try:
dest = open (outfile, 'a')
except IOError, err:
error (_("can't open `%s': %s") % (outfile, str (err).decode (charset)))
# appending the reference list
try:
refs = open (reffile, 'r')
except IOError, err:
error ("`%s': %s" % (reffile, str (err).decode (charset)))
while 1:
line = refs.readline ()
if line == '': break
dest.write (line)
refs.close ()
dest.close ()
try:
os.remove (reffile)
except:
warning (_("can't remove `%s'") % reffile)
print _("Done").encode (charset)
|