0

I want to replace fraction with unicode characters by lookup if it in the dictionary but can't find the way to do it.

fixs = {
    '1/2': '¹⁄₂',
    '1/4': '¹⁄₄',
    '3/8': '³⁄₈',
     ...
    # '': '⁰¹²³⁴⁵⁶⁷⁸⁹⁄₀₁₂₃₄₅₆₇₈₉',
}

My current solution is obviously bad

def fix_fraction(string):
    return string.replace('1/2', '¹⁄₂').replace('1/4', '¹⁄₄').replace('3/8', '³⁄₈')

The input of fix_fraction might have text mixed in with unknown position so I can't just split the fraction out and I can't write regex successfully.

Sample usage:

print(fix_fraction('item A d=1/2″'))
print(fix_fraction('item B d=3/8 m'))

item A d=¹⁄₂″                                                                                                                                                                                          
item B d=³⁄₈ m

Dictionary is expected to have no more than 100 entries but ultimate solution that support any fraction is also welcomed.

Any idea how to do this correctly?

cs95
  • 379,657
  • 97
  • 704
  • 746
wizzup
  • 2,361
  • 20
  • 34
  • It can be done using unicode subscripts and superscripts, something like: unichr(0x2070 + v) where v is a digit. – axaroth Jul 27 '17 at 12:51

1 Answers1

1

One possible approach is to just loop over your fixs and replace items in the text within the loop:

In [938]: text = 'item B d=3/8 m'

In [939]: for k in fixs:
     ...:     text = text.replace(k, fixs[k]) 
     ...:     

In [940]: text
Out[940]: 'item B d=³⁄₈ m'
cs95
  • 379,657
  • 97
  • 704
  • 746