Created
October 16, 2014 09:55
-
-
Save scraperdragon/6341ec0949a9f7c3b834 to your computer and use it in GitHub Desktop.
text to unicode subscript / superscript
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
# -*- coding: utf-8 | |
from __future__ import unicode_literals | |
import warnings | |
import unicodedata | |
def build_lookup(macro, micro): | |
assert len(macro) == len(micro), (len(macro), len(micro)) | |
output = {} | |
for pair in zip(macro, micro): | |
if pair[1] != ' ': | |
output[pair[0]] = pair[1] | |
return output | |
def translate(macro, trans): | |
output = [] | |
for char in macro: | |
try: | |
output.append(trans[char]) | |
except KeyError: # wrong type of error | |
output.append(char) | |
cat = unicodedata.category(char) | |
if cat in ['Zs']: | |
continue | |
warnings.warn('{!r} not available as (sub|super)script'.format(char)) | |
return ''.join(output) | |
n_num = "0123456789+-=()" | |
u_num = "⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾" | |
d_num = "₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎" | |
n_low = "abcdefghijklmnopqrstuvwxyz" | |
u_low = "ᵃᵇᶜᵈᵉᶠᵍʰⁱʲᵏˡᵐⁿᵒᵖ ʳˢᵗᵘᵛʷˣʸᶻ" | |
d_low = "ₐ ₑ ₕᵢⱼₖₗₘₙₒₚ ᵣₛₜᵤᵥ ₓ " | |
n_hi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
u_hi = "ᴬᴮ ᴰᴱ ᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾ ᴿ ᵀᵁⱽᵂ " | |
d_hi = " " | |
# n_grk="αβγδεζηθικλμνξοπρςστυφχψωɸ" | |
# u_grk="ᵅᵝᵞᵟᵋ ᶿᶥ ᵠᵡ ᶲ" | |
# d_grk=" ᵦᵧ ᵨ ᵩᵪ " | |
n = n_num+n_low+n_hi | |
u = u_num+u_low+u_hi | |
d = d_num+d_low+d_hi | |
utrans = build_lookup(n, u) | |
dtrans = build_lookup(n, d) | |
def sub(s): | |
return translate(s, dtrans) | |
def sup(s): | |
return translate(s, utrans) | |
if __name__ == '__main__': | |
print sup('hello world') | |
print sub('hello world') | |
print sup('HELLO WORLD') | |
print sub('HELLO WORLD') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment