Created
October 27, 2020 19:28
-
-
Save jhtang2/5a53e4926b338461f810aa02c65b51d0 to your computer and use it in GitHub Desktop.
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
import re | |
number = r'\d+(,\d{3})*\.*\d*' #$790,000 | |
amount = r'thousand|million|billion' #$12.2 million example | |
word_re = rf'\${number}(-|\sto\s|–)?(\$*{number})\s?({amount})' | |
value_re = rf'\${number}' | |
def parse_word_syntax(string): | |
value_string = re.search(number,string).group() | |
value = float(value_string.replace(',','')) | |
word = re.search(amount,string,flags=re.I).group().lower() | |
word_value = word_to_value(word) | |
return value * word_value | |
def word_to_value(word): | |
value_dict ={'thousand':1000,'million':1000000,'billion':1000000000} | |
return value_dict[word] | |
def parse_value_syntax(string): | |
value_string = re.search(number,string).group() | |
value = float(value_string.replace(',','')) | |
return value | |
def money_conversion(money): | |
if money == 'N/A': | |
return None | |
if isinstance(money,list): | |
money = money[0] | |
word_syntax = re.search(word_re,money,flags=re.I) | |
value_syntax = re.search(value_re,money) | |
if word_syntax: | |
print('converting word object to numerics') | |
return parse_word_syntax(word_syntax.group()) | |
elif value_syntax: | |
print('converting float objects to numerics') | |
return parse_value_syntax(value_syntax.group()) | |
else: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment