Markdown lines count in Streamlit or in Python

19 Views Asked by At

I am working on building two customized st.markdown-s with defined height, width, and background color. The height of these two st.markdown-s should be the same and equal to the height of the longest markdown (for example: if the first markdown has 10 lines and the second - 7, the height of these two markdowns should correspond to 10 lines.) Markdown example:

st.markdown(
    f"""
    <div style="background-color:#e7efe0;margin: 10px; padding:10px;border-radius:10px; height:{max lines count}em; width: 35em; margin:0 auto">
        <p style="color:#333333;text-align:left;font-size:12px;">Text here</h3>
    </div>
    """,
    unsafe_allow_html=True
)

My algorithm (it is working not accurately): I tried to calculate the lines count by approximating the number of characters one line can fit . For example, a line can fit max 30 characters, we wrap the text when the number of characters exceed this limit. My function's code:

def count_lines(sentence, max_num=22):
    for word in words:
        word_length = len(word)
        if current_line_length == 0:
            current_line_length += word_length
        elif current_line_length + 1 + word_length <= max_num:
            current_line_length += 1 + word_length
        else:
            lines += 1
            current_line_length = word_length
    return lines

However, each character has its own width: for instance, the width of "," and letter "m" is different. I am trying to find a more efficient solution, some function that can determine the pixel count of a string. If the string has more pixels than the width of the markdown, then this string should be wrapped.

1

There are 1 best solutions below

0
MrSmith42 On

I thing you cannot get much more efficient since you need to calculate the line-length at some point to compare it with max_num.

This reduces the calulation a bit (not much).

def count_lines(sentence, max_num=22):
    current_line_length = -1     // compensated the 1 added with the first word
    for word in words:
        word_length = len(word)
        current_line_length += 1 + word_length
        if current_line_length > max_num:
            lines += 1
            current_line_length = word_length
    return lines

I think the len(word)-method has potential for speedup.

  • use a lookup-table for each character
  • use a hash-map for frequent words