Guest User

Untitled

a guest
Jan 20th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. def parse_numeric_string(s):
  2.  
  3. if isinstance(s, int): s = str(s)
  4.  
  5. amount = None
  6. currency = ''
  7. multiplier = 1.0
  8.  
  9. for token in s.split(' '):
  10.  
  11. token = token.lower()
  12.  
  13. # Extract multipliers from their string names/abbrevs
  14. if token in ['million','m','mm']:
  15. multiplier = 1e6
  16. # ... or you could use a dict:
  17. # multiplier = {'million': 1e6, 'm': 1e6...}.get(token, 1.0)
  18.  
  19. # Assume anything else is some string format of number/int/float/scientific
  20. try:
  21. token = token.replace(',', '')
  22. amount = float(token)
  23. except:
  24. pass # Process your parse failures...
  25.  
  26. # Return a tuple, or whatever you prefer
  27. return (currency, amount * multiplier)
  28.  
  29. parse_numeric_string("$ 1,350,000")
  30. parse_numeric_string("1.35 MM $")
  31. parse_numeric_string("$ 1.35 M")
  32. parse_numeric_string(1350000)
  33.  
  34. (?<=$ )([d,]+)
  35.  
  36. ([d.]+)(?= MM $)
  37.  
  38. (?<=$ )([d.]+)(?= M)
  39.  
  40. ([d]+)
Add Comment
Please, Sign In to add comment