-
Notifications
You must be signed in to change notification settings - Fork 96
/
amount_parsing.py
45 lines (40 loc) · 1.49 KB
/
amount_parsing.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
import re
from beancount.core.number import D
from beancount.core.amount import Amount
def parse_negative_parentheses(x):
"""Parses a string in parentheses as a negative."""
m = re.fullmatch(r'^\((.*)\)$', x)
if m is not None:
return -1, m.group(1).strip()
return 1, x
def parse_possible_negative(x):
x = x.strip()
m = re.fullmatch(r'^(-|\+)(.*)$', x)
if m is not None:
sign = -1 if m.group(1) == '-' else 1
return sign, m.group(2).strip()
return parse_negative_parentheses(x)
def parse_number(x):
"""Parses a number in the format of the CSV file.
A number in parentheses is interpreted as a negative number.
"""
sign, number_str = parse_possible_negative(x)
return sign * D(number_str)
def parse_amount(x, assumed_currency=None):
"""Parses a number and currency."""
if not x:
return None
sign, amount_str = parse_possible_negative(x)
m = re.fullmatch(r'(?:[(][^)]+[)])?\s*([\$€£])?((?:[0-9](?:,?[0-9])*|(?=\.))(?:\.[0-9]+)?)(?:\s+([A-Z]{3}))?', amount_str)
if m is None:
raise ValueError('Failed to parse amount from %r' % amount_str)
if m.group(1):
currency = {'$': 'USD', '€': 'EUR', '£': 'GBP'}[m.group(1)]
elif m.group(3):
currency = m.group(3)
elif assumed_currency is not None:
currency = assumed_currency
else:
raise ValueError('Failed to determine currency from %r' % amount_str)
number = D(m.group(2))
return Amount(number * sign, currency)