fork(1) download
  1. import re
  2. my_str = "This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour." # A free text
  3.  
  4. def replace_fractions(text):
  5. fraction_dict = {
  6. '1/2': 'half',
  7. '1/4': 'quarter',
  8. '3/4': 'three quarters',
  9. '2/3': 'two thirds',
  10. }
  11. return re.sub(r'(?<!\d)(?<!\d/)[0-9]/[0-9]{1,2}(?!/?\d)', lambda x: fraction_dict.get(x.group(), x.group()), text)
  12.  
  13. current_result = replace_fractions("This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour.")
  14. print(current_result)
Success #stdin #stdout 0.03s 9664KB
stdin
Standard input is empty
stdout
This is a half quarter. Press 1/2/3. He drove a car for halfhour.