-
Notifications
You must be signed in to change notification settings - Fork 1
/
parse.py
49 lines (41 loc) · 1.39 KB
/
parse.py
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
# encoding: utf-8
"""
Parse module for parsing citations into structured data. Currently this uses
the Parsley library to do this, the grammars are defined in the grammars/
folder and cycled through until one is found that works.
to_dict will convert the Reference named tuple into a dictionary, which allows
for easy transformation into JSON.
"""
import collections
import glob
import re
import parsley
DASHES = ['-', u'–']
fields = "ref names year title journal edition pages doi".split()
Reference = collections.namedtuple("Reference", ' '.join(fields))
def normalize(string):
"""Normalize whitespace."""
string = string.strip()
string = re.sub(r'\s+', ' ', string)
return string
parsers = []
for gname in glob.glob("grammars/*.parsley"):
with open(gname) as gfile:
grammar = unicode(gfile.read())
parser = parsley.makeGrammar(grammar, dict(DASHES=DASHES,
Reference=Reference, normalize=normalize))
parsers.append(parser)
def parse(text):
"""
Attempt to parse data into a Reference named tuple. Returns None if it
fails.
"""
for parser in parsers:
try:
return parser(text).line()
except Exception as e:
print e.message
pass
def to_dict(s):
"""Turns a citation into a dictioarny that can then be turned into JSON."""
return parser(s).line()._asdict()