|
| 1 | +# https://tex.stackexchange.com/questions/124874/converting-to-bibitem-in-latex |
| 2 | +# filename: bibtex2item.py |
| 3 | +# python2 bibtex2item.py < refs.bib > bibitem.txt |
| 4 | +import sys |
| 5 | + |
| 6 | +bibtex = sys.stdin.read() |
| 7 | +r = bibtex.split('\n') |
| 8 | +i = 0 |
| 9 | +while i < len(r): |
| 10 | + line = r[i].strip() |
| 11 | + if not line: i += 1 |
| 12 | + if '@' == line[0]: |
| 13 | + code = line.split('{')[-1][:-1] |
| 14 | + title = venue = volume = number = pages = year = publisher = authors = None |
| 15 | + output_authors = [] |
| 16 | + i += 1 |
| 17 | + while i < len(r) and '@' not in r[i]: |
| 18 | + line = r[i].strip() |
| 19 | + #print(line) |
| 20 | + if line.startswith("title"): |
| 21 | + title = line.split('{')[-1][:-2] |
| 22 | + elif line.startswith("journal"): |
| 23 | + venue = line.split('{')[-1][:-2] |
| 24 | + elif line.startswith("volume"): |
| 25 | + volume = line.split('{')[-1][:-2] |
| 26 | + elif line.startswith("number"): |
| 27 | + number = line.split('{')[-1][:-2] |
| 28 | + elif line.startswith("pages"): |
| 29 | + pages = line.split('{')[-1][:-2] |
| 30 | + elif line.startswith("year"): |
| 31 | + year = line.split('{')[-1][:-2] |
| 32 | + elif line.startswith("publisher"): |
| 33 | + publisher = line.split('{')[-1][:-2] |
| 34 | + elif line.startswith("author"): |
| 35 | + authors = line[line.find("{")+1:line.rfind("}")] |
| 36 | + for LastFirst in authors.split('and'): |
| 37 | + lf = LastFirst.replace(' ', '').split(',') |
| 38 | + if len(lf) != 2: continue |
| 39 | + last, first = lf[0], lf[1] |
| 40 | + output_authors.append("{}, {}.".format(last.capitalize(), first.capitalize()[0])) |
| 41 | + i += 1 |
| 42 | + |
| 43 | + print "\\bibitem{%s}" % code |
| 44 | + if len(output_authors) == 1: |
| 45 | + print output_authors[0] + " {}. ".format(title), |
| 46 | + else: |
| 47 | + print ", ".join(_ for _ in output_authors[:-1]) + " & " + output_authors[-1] + " {}. ".format(title), |
| 48 | + if venue: |
| 49 | + print "{{\\em {}}}.".format(" ".join([_.capitalize() for _ in venue.split(' ')])), |
| 50 | + if volume: |
| 51 | + sys.stdout.write(" \\textbf{{{}}}".format(volume)) |
| 52 | + if pages: |
| 53 | + sys.stdout.write(", {}".format(pages) if number else " pp. {}".format(pages)) |
| 54 | + if year: |
| 55 | + sys.stdout.write(" ({})".format(year)) |
| 56 | + if publisher and not venue: |
| 57 | + print "({},{})".format(publisher, year) |
| 58 | + print |
| 59 | + print |
0 commit comments