Skip to content

Instantly share code, notes, and snippets.

@CaptSolo
Created December 14, 2009 03:11
Show Gist options
  • Save CaptSolo/255743 to your computer and use it in GitHub Desktop.
Save CaptSolo/255743 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
bfind.py - Search for references matching given text
in BibTeX files and on BibSonomy.
Author: Uldis Bojars
http://captsolo.net
"""
import re
import sys
import urllib, urllib2
class BibSonomy(object):
query = "http://www.bibsonomy.org/bib/search/%s"
def find_items(self, keyword):
param = ( urllib.quote_plus(keyword) )
print param
try:
req = urllib2.urlopen(self.query % param)
return req.read()
except URLError, e:
print e.code
print e.read()
print "------------------------------------------------------"
def bibtex_files():
LISTFILE = "bibtex.lst"
f = open(LISTFILE)
for line in f.readlines():
line = line.strip()
if len(line)>0:
yield line
f.close()
def find_entries(fnames):
for fname in fnames:
f = open(fname)
brace_cnt = 0
buffer = ""
in_entry = False
for line in f:
if not in_entry:
if line.strip().startswith("@"):
in_entry = True
else:
continue
if in_entry:
buffer += line
# XXX - assumption: there is opening brace on the 1st line (which starts with @)
# NOTE: if this assumption not true, entry will be truncated
brace_cnt += line.count("{") - line.count("}")
assert(brace_cnt>=0)
if brace_cnt == 0:
# assume we reached the end of the entry
yield (buffer, fname)
buffer = ""
in_entry = False
f.close()
# TODO - create a dynamic GUI for this code
# TODO - write some tests!
class EntryStore(object):
def __init__(self):
self.store = []
def append(self, entries):
for item in entries:
self.store.append(item)
def item_list(self):
return (item for item in self.store)
def find_items(self, keyword):
t_re = re.compile(keyword, re.I)
return (item for item in self.store if t_re.search(item[0]) is not None)
def find_in_bibtex(terms):
x = EntryStore()
x.append(find_entries(bibtex_files()))
res = x.find_items(terms)
for item in res:
print item[1]
print item[0]
def find_in_bibsonomy(terms):
y = BibSonomy()
print y.find_items(terms)
def main():
if len(sys.argv)>1:
terms = sys.argv[1]
else:
print "Demo mode: searching for 'amst'"
print
terms = "amst"
# search in bibtex files (listed in the file)
# find_in_bibtex(terms)
# search in Bibsonomy
find_in_bibsonomy(terms)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment