Attachment 'simplebibtex.py'

Download

   1 #FORMAT python
   2 # -*- coding: UTF-8 -*-
   3 """
   4    MoinMoin - Simple bibtex parser
   5 
   6    Based on Matt Cooper's keyval parser
   7    
   8    Copyright: 2010 by Ryota Tomioka
   9    Copyright: 2006 by Matt Cooper <macooper@vt.edu>
  10    License: GNU GPL
  11    Version: 1.0
  12 """
  13 import re
  14 from MoinMoin import wikiutil
  15 
  16 
  17 def latex2unicode(str):
  18     tab = {"\\\"u": "&uuml;",
  19            "\\\"o": "&ouml;",
  20            "\\\"e": "&euml;",
  21            "\\\"a": "&auml;",
  22            "\\o"  : "&oslash;",
  23            "\\O"  : "&Oslash;",
  24            "~"    : " ",
  25            "\\'e" : "&eacute;",
  26            "\\`e" : "&egrave;"}
  27 
  28     for key in tab.keys():
  29         str = str.replace(key, tab[key])
  30     return str
  31 
  32 def removepar(str):
  33     str = str.replace("{","").replace("}","")
  34     return str
  35 
  36 class Bibitem:
  37     def __init__(self):
  38         self.bib =  {"title":"", "author":"", "year":"", "url":""}
  39 
  40     def setValue(self, key, val):
  41         self.bib[key.lower().strip()] = removepar(val.lstrip('" ').rstrip(' ",'))
  42     
  43     def isReady(self):
  44         return len(self.bib["author"])>0 and len(self.bib["title"])>0 and len(self.bib["year"])>0
  45 
  46     def format_author(self):
  47         authors = self.bib["author"].split(" and ")
  48         result = []
  49         for author in authors:
  50             result.append(latex2unicode(author.strip()))
  51         return ", ".join(result)+"."
  52     
  53     def format_title(self):
  54         title = latex2unicode(self.bib["title"]);
  55         return "<a href=\"%s\">%s</a>." % (self.bib["url"], title)
  56 
  57 
  58 
  59 class BibitemJournal(Bibitem):
  60     def __init__(self):
  61         Bibitem.__init__(self)
  62         self.bib["journal"]=""
  63         self.bib["volume"]=""
  64         self.bib["number"]=""
  65         self.bib["pages"]=""
  66 
  67     def format(self):
  68         if len(self.bib["title"])>0:
  69             return "<li>%s %s %s %s %s.</li>" % (self.format_author(), self.format_title(), self.format_journal(), self.format_volnumpages(), self.bib["year"])
  70         else:
  71             return ""
  72 
  73     def format_journal(self):
  74         if len(self.bib["journal"])>0:
  75             return "<i>%s</i>," % (self.bib["journal"])
  76         else:
  77             return ""
  78 
  79     def format_volnumpages(self):
  80         result = ""
  81         if len(self.bib["volume"])>0:
  82             result += "<b>%s</b>" % self.bib["volume"]
  83         if len(self.bib["number"])>0:
  84             result += "(%s)" % self.bib["number"]
  85         if len(self.bib["pages"])>0:
  86             result += ":%s," % self.bib["pages"]
  87         elif len(result)>0:
  88             result += ","
  89         return result
  90 
  91 class BibitemBook(Bibitem):
  92     def __init__(self):
  93         Bibitem.__init__(self)
  94         self.bib["publisher"]=""
  95         self.bib["address"]=""
  96 
  97     def format(self):
  98         if len(self.bib["title"])>0:
  99             return "<li>%s <i>%s</i> %s %s.</li>" % (self.format_author(), self.format_title(), self.format_pubadd(), self.bib["year"])
 100         else:
 101             return ""
 102         
 103     def format_pubadd(self):
 104         result=""
 105         if len(self.bib["publisher"])>0:
 106             result += "%s," % self.bib["publisher"]
 107         if len(self.bib["address"])>0:
 108             result += " %s," % self.bib["address"]
 109         return result
 110 
 111 class BibitemTechreport(Bibitem):
 112     def __init__(self):
 113         Bibitem.__init__(self)
 114         self.bib["institution"]=""
 115 
 116     def format(self):
 117         if len(self.bib["title"])>0:
 118             return "<li>%s %s %s %s.</li>" % (self.format_author(), self.format_title(), self.format_institution(), self.bib["year"])
 119         else:
 120             return ""
 121 
 122     def format_institution(self):
 123         if len(self.bib["institution"])>0:
 124             return "Technical report, %s," % self.bib["institution"]
 125         else:
 126             return ""
 127 
 128 class BibitemInCollection(BibitemBook):
 129     def __init__(self):
 130         Bibitem.__init__(self)
 131         self.bib["booktitle"]=""
 132         self.bib["pages"]=""
 133         self.bib["publisher"]=""
 134         self.bib["address"]=""
 135 
 136     def format(self):
 137         if len(self.bib["title"])>0:
 138             return "<li>%s %s %s %s %s %s.</li>" % (self.format_author(), self.format_title(), self.format_booktitle(), self.format_pages(), self.format_pubadd(), self.bib["year"])
 139         else:
 140             return ""
 141 
 142     def format_booktitle(self):
 143         if len(self.bib["booktitle"])>0:
 144             return "In <i>%s</i>," % self.bib["booktitle"]
 145         else:
 146             return ""
 147 
 148     def format_pages(self):
 149         if len(self.bib["pages"])>0:
 150             return "pages %s." % self.bib["pages"]
 151         else:
 152             return ""
 153 
 154        
 155 class Parser:
 156     """
 157         Key-value pairs parser
 158         "Key" is anything before the delimiter,
 159         "Value" is everything after (including more delimiters)
 160         If a delimiter isn't found, the line is not turned into a key-value pair
 161     """
 162     
 163     parsername = "KeyValueParser"
 164     
 165     def __init__(self, raw, request, **kw):
 166         self.request = request
 167         self.form = request.form
 168         self.raw = raw
 169         self._ = request.getText
 170         self.args = kw.get('format_args', '')
 171     
 172         attrs, msg = wikiutil.parseAttributes(request, self.args)
 173         self.delim = attrs.get('delim', '')[1:-1]
 174 
 175 
 176     def format(self, formatter):
 177         linesep   = "\n"
 178         delimiter = self.delim or "="
 179         
 180         # split the raw input into lines
 181         lines = self.raw.split("\n")
 182         
 183         bib=None
 184         result = []
 185         while lines:
 186             line = lines.pop(0)
 187             if len(line.strip())>0 and line.strip()[0]=="@":
 188                 # Output the last bibitem
 189                 if bib is not None:
 190                     result.append(bib.format())
 191 
 192                 # New bibitem begins
 193                 type = line[1:-1].split("{",1)[0]
 194                 if type.lower()=="incollection" or type.lower()=="inproceedings" or type.lower()=="conference":
 195                     bib=BibitemInCollection()
 196                 elif type.lower()=="book":
 197                     bib=BibitemBook()
 198                 elif type.lower()=="techreport":
 199                     bib=BibitemTechreport()
 200                 else:
 201                     bib=BibitemJournal()
 202             
 203             elif line.find(delimiter) > -1:
 204                 (k,v) = line.split(delimiter, 1)
 205                 
 206                 if bib is not None:
 207                     bib.setValue(k,v)
 208                 else:
 209                     result.append("Strange line [%s] found\n" % line)
 210                 
 211             # if there is no delimiter...
 212             else:
 213                 if bib is not None and bib.isReady():
 214                     result.append(bib.format())
 215                     bib = None
 216 
 217         if bib is not None:
 218             result.append(bib.format())
 219 
 220         self.raw = "<ul>\n%s</ul>\n" % linesep.join(result)
 221         self.request.write(formatter.rawHTML(self.raw))

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2010-11-27 08:37:18, 39.5 KB) [[attachment:screen.png]]
  • [get | view] (2010-11-27 08:31:00, 6.8 KB) [[attachment:simplebibtex.py]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.