Created
September 8, 2011 15:36
-
-
Save fmoralesc/1203698 to your computer and use it in GitHub Desktop.
minimal regex based bibtex parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
# usage: script.py QUERY BIBFILE | |
import sys | |
import re | |
title_search = re.compile("\s*[Tt]itle\s*=\s*{(?P<title>\S.*)},\n") | |
booktitle_search = re.compile("\s*[Bb]ooktitle\s*=\s*{(?P<title>\S.*)},\n") | |
author_search = re.compile("\s*[Aa]uthor\s*=\s*{(?P<author>\S.*)},\n") | |
id_search = re.compile(".*{\s*(?P<id>.*),") | |
def parse_bibfile_for_vim_with_search(query): | |
entries = [] | |
# let's make this thing fast! | |
if query != "": | |
id_search = re.compile(".*{\s*(?P<id>" + query + "\S.*),") | |
for entry in [i for i in re.split("\n@", text)]: | |
entry_dict = {} | |
i1 = id_search.match(entry) | |
if i1: | |
entry_dict["word"] = i1.group("id") | |
title = "" | |
author = "" | |
i2 = title_search.search(entry) | |
if i2: | |
title = i2.group("title") | |
else: | |
i3 = booktitle_search.search(entry) | |
if i3: | |
title = i3.group("title") | |
i4 = author_search.search(entry) | |
if i4: | |
author = i4.group("author") | |
entry_dict["menu"] = "- ".join([author, title]) | |
if entry_dict != {}: | |
entries.append(entry_dict) | |
return entries | |
if __name__ == "__main__": | |
with open(sys.argv[2]) as f: | |
text = f.read() | |
print len(parse_bibfile_for_vim_with_search(sys.argv[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment