strangedev
11/23/2019 - 1:01 AM

Converting emoji digits to regular ones in Python

Converting emoji digits to regular ones in Python

#!/bin/python3
import logging
from typing import Optional
from copy import deepcopy

__author__ = "Noah Hummel <oss@noahhummel.consulting>"

log = logging.getLogger("noahhummel.util.emoji.digits")

digits = [
    ["\u0030", "\uFE0F", "\u20E3"],  #0
    ["\u0031", "\uFE0F", "\u20E3"],  #1
    ["\u0032", "\uFE0F", "\u20E3"],  #2
    ["\u0033", "\uFE0F", "\u20E3"],  #3
    ["\u0034", "\uFE0F", "\u20E3"],  #4
    ["\u0035", "\uFE0F", "\u20E3"],  #5
    ["\u0036", "\uFE0F", "\u20E3"],  #6
    ["\u0037", "\uFE0F", "\u20E3"],  #7
    ["\u0038", "\uFE0F", "\u20E3"],  #8
    ["\u0039", "\uFE0F", "\u20E3"]  #9
]

windowSize = max(map(len, digits))


def whichDigit(d: str) -> Optional[int]:
    for iDigit in range(len(digits)):
        emoji = digits[iDigit]
        match = True
        maxCursor = min((len(emoji), len(d)))
        for iCursor in range(maxCursor):
            match &= emoji[iCursor] == d[iCursor]
        if match:
            return str(iDigit), maxCursor - 1
    return None, 0


def slidingWindow(fn, length: int, longStr: str) -> str:
    iCursor = 0
    tmpStr = deepcopy(longStr)
    while len(longStr) >= length:
        window = longStr[:length]
        match, size = fn(window)
        if match:
            yield match
            longStr = longStr[size:]
        else:
            yield longStr[0]
        longStr = longStr[1:]
    for rest in longStr:
        yield rest


def convertEmojiDigits(longStr: str) -> str:
    return "".join([c for c in slidingWindow(whichDigit, windowSize, longStr)])


if __name__ == "__main__":
    import sys
    import fileinput
    try:
        for line in fileinput.input():
            print(convertEmojiDigits(line))
    except KeyboardInterrupt:
        sys.exit(0)