Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- from collections import OrderedDict
- def latex2func(s, udict=OrderedDict()):
- class make_xlat(object):
- def __init__(self, *args, **kwargs):
- self.adict = OrderedDict((
- (r'\left' , ''),
- (r'\right' , ''),
- (r'\cdot' , '*'),
- ('^' , '**'),
- (' ' , ''),
- ('{' , '('),
- ('}' , ')'),
- (r'(\d+)([A-Za-z]\d*\w*)' , r'\1*\2'),
- (r'\((\d+)\)' , r'\1'),
- ))
- self.adict.update(*args, **kwargs)
- self.grp_lookup = self.make_grp_lookup()
- self.rx = self.make_rx()
- def make_grp_lookup(self):
- grps = {}
- for k,v in self.adict.items():
- i = max(grps.keys())+1 if grps else 0
- grps.update({i+j: k for j in range(len(re.findall(r'\\\d+', v)))})
- return grps
- def make_rx(self):
- l = []
- for k, v in self.adict.items():
- if not re.search(r'\\\d+', v):
- l.append(''.join(map(re.escape, k)))
- else:
- l.append(k)
- return re.compile('|'.join(l))
- def one_xlat(self, match):
- try: # Simple string replacement
- return self.adict[match.group(int(0))]
- except: # Subpattern group replacement
- i, m = zip(*[(i, v) for i, v in enumerate(match.groups()) if v is not None])
- t = self.adict[self.grp_lookup[i[0]]] # Assumes all indicies are the same, if not, something went wrong
- for i, g in enumerate(m):
- t = t.replace(r'\{}'.format(i+1), g)
- return t
- def __call__(self, txt):
- return self.rx.sub(self.one_xlat, txt)
- translate = make_xlat(udict)
- while translate(s) is not s:
- s = translate(s)
- s = s.split('=')
- args = re.sub(r'.*\((.*)\)', r'\1', s[0])
- eqn = s[1]
- return eqn
Advertisement
Add Comment
Please, Sign In to add comment