Advertisement
jxsl13

Example: Parsing arithmetic operations with the re library.

Aug 21st, 2019
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import re
  4. import string
  5.  
  6. def remove_whitespace(in_string: str):
  7.     return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))
  8.  
  9. def parse_operation(expression):
  10.     # convert to string
  11.     ss = f"{expression}"
  12.     ss = remove_whitespace(ss)
  13.    
  14.     # passed value is a simple int or float
  15.     try:
  16.         return int(ss)
  17.     except Exception:
  18.         pass
  19.  
  20.     try:
  21.         return float(ss)
  22.     except Exception:
  23.         pass
  24.  
  25.     # passed value is either int or float followed by a %
  26.     match = re.fullmatch(r"([\d]+(\.[\d]+)?)%", ss)
  27.     if match:
  28.         try:
  29.             return int(match.group(1))
  30.         except Exception:
  31.             return float(match.group(1))
  32.    
  33.     # passed value is (int/float)(operator)(int/float)
  34.     match_list = []
  35.     match_list.append(re.fullmatch(r"([\d]+)%?([+\-*/])([\d]+)%?", ss))
  36.     match_list.append(re.fullmatch(r"([\d]+\.[\d]+)%?([+\-*/])([\d]+\.[\d]+)%?", ss))
  37.    
  38.  
  39.     for match in match_list:
  40.         if match:
  41.             try:
  42.                 x = int(match.group(1))
  43.                 y = int(match.group(3))
  44.             except Exception:
  45.                 x = float(match.group(1))
  46.                 y = float(match.group(3))
  47.  
  48.             operator = match.group(2)
  49.  
  50.             if operator == '+':
  51.                 return x + y
  52.             elif operator == '-':
  53.                 return x - y
  54.             elif operator == '*':
  55.                 return x * y
  56.             elif operator == '/':
  57.                 return x / y
  58.        
  59.     return None
  60.  
  61.  
  62.  
  63. l1 = ['0', '10+7', '20', '30', '40+20', '6']
  64. l2 = [0, '10+7', 20, 30, '40+20', 6]
  65.  
  66. l1_result = [parse_operation(x) for x in l1]
  67. l2_result = [parse_operation(x) for x in l2]
  68.  
  69. print("l1", l1_result)
  70. print("l2", l2_result)
  71.  
  72.  
  73. l3 = ['10%', '20%', 5, 14, 16]
  74. l4 = ['10%+30%', '20%-7%', '5', '14', '16']
  75.  
  76. l3_result = [parse_operation(x) for x in l3]
  77. l4_result = [parse_operation(x) for x in l4]
  78.  
  79. print("l3", l3_result)
  80. print("l4", l4_result)
  81.  
  82.  
  83. l5 = ['10% - 90%', '15.99 + 33.0', '12 / 3', '99 / 34', '25 * 4', '5', '6', '9.99']
  84. l5_result = [parse_operation(x) for x in l5]
  85.  
  86. print("l5", l5_result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement