Streamlit 或 Python 中的 Markdown 行数

问题描述 投票:0回答:1

我正在构建两个自定义的 st.markdown-s,具有定义的高度、宽度和背景颜色。这两个 st.markdown-s 的高度应该相同并且等于最长的 markdown 的高度(例如:如果第一个 markdown 有 10 行,第二个 - 7 行,那么这两个 markdown 的高度应该对应于 10行。) 降价示例:

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
)

我的算法(它工作不准确) 我尝试通过近似一行可以容纳的字符数来计算行数。例如,一行最多可以容纳 30 个字符,当字符数超过此限制时,我们将文本换行。 我的函数代码:

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

但是,每个字符都有自己的宽度:例如,“,”和字母“m”的宽度是不同的。 我试图找到一个更有效的解决方案,一些可以确定字符串像素数的函数。如果字符串的像素多于 markdown 的宽度,则应将该字符串换行。

html css algorithm markdown streamlit
1个回答
0
投票

我认为你无法获得更高的效率,因为你需要在某个点计算行长度以将其与 max_num 进行比较。

这稍微减少了计算量(不多)。

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
        else:
            current_line_length += 1 + word_length
            if current_line_length > max_num:
                lines += 1
                current_line_length = word_length
    return lines
© www.soinside.com 2019 - 2024. All rights reserved.