Show colored text in streamlit

I am using the following function from https://stackoverflow.com/questions/32500167/how-to-show-diff-of-two-string-sequences-in-colors to find the difference in color between two strings. The function is:

from colorama import *
import numpy as np

inv_WHITE = Fore.WHITE[::-1]
inv_RED = Fore.RED[::-1]
inv_GREEN = Fore.GREEN[::-1]

def edDistDp(y, x):
    res = inv_WHITE
    D = np.zeros((len(x) + 1, len(y) + 1), dtype=int)
    D[0, 1:] = range(1, len(y) + 1)
    D[1:, 0] = range(1, len(x) + 1)
    for i in range(1, len(x) + 1):
        for j in range(1, len(y) + 1):
            delt = 1 if x[i - 1] != y[j - 1] else 0
            D[i, j] = min(D[i - 1, j - 1] + delt, D[i - 1, j] + 1, D[i, j - 1] + 1)
    # print D

    # iterate the matrix's values from back to forward
    i = len(x)
    j = len(y)
    while i > 0 and j > 0:
        diagonal = D[i - 1, j - 1]
        upper = D[i, j - 1]
        left = D[i - 1, j]

        # check back direction
        direction = (
            "\\"
            if diagonal <= upper and diagonal <= left
            else "<-"
            if left < diagonal and left <= upper
            else "^"
        )
        # print "(",i,j,")",diagonal, upper, left, direction
        i = i - 1 if direction == "<-" or direction == "\\" else i
        j = j - 1 if direction == "^" or direction == "\\" else j
        # Colorize caracters
        if direction == "\\":
            if D[i + 1, j + 1] == diagonal:
                res += x[i] + inv_WHITE
            elif D[i + 1, j + 1] > diagonal:
                res += y[j] + inv_RED
                # res += x[i] + inv_GREEN
            else:
                # res += x[i] + inv_GREEN
                res += y[j] + inv_RED
        elif direction == "<-":
            res += x[i] + inv_RED
        elif direction == "^":
            res += y[j] + inv_RED
    return res[::-1]

when I write the output of this function using st.write(edDistDp('hat','cat')), I get the following output. m23;1[ehm53;1[eam53;1[etm53;1[e I know that colorama is used to color strings in the terminal. Is there a way to solve this issue and have the difference between (hat) and (cat) which is thw two letters (h,c) highlighted in another color and output in streamlit?

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.