簡體   English   中英

Python - Markdown 表 - 在 Streamlit 中僅顯示第一行

[英]Python - Markdown Table - Only showing first row in Streamlit

如果需要,我可以嘗試生成一個可重現的示例,但我想我會先展示代碼。 我正在使用 Streamlit 和 function,它采用 JSON 文件並在 markdown 中生成一個表:

      table = f"""
      |Rank|Title|Value|{"# words|" * n_words}{"Similarity|" * distance}
      |--|--|--|--|--|
      """
        for i, el in enumerate(data):
            line = f"""|{i + 1}|**{el["title"]}**|£{el["value"]:,}|"""
            if n_words:
                line += f"""{str(el["n_words"])}|"""
            if distance:
                line += f"""{str(round(el["distance"], 2))}"""
            line = f"""{line}
                """
            table += line
    
        st.markdown(table)

出於某種原因,它適用於第一行,但不適用於任何其他行。 我在做什么明顯錯誤的事情嗎?

在此處輸入圖像描述

非常感謝!

你有兩個問題。

  1. markdown的調用需要減少縮進,以便在 for 循環結束后調用它,而不是在第一個循環結束時調用。
  2. 您需要從字符串文字中刪除縮進。

具體來說,這條線...

line = f"""{line}
                """

...導致第一行之后的每一行縮進 16 個空格。 當然,Markdown 將縮進視為縮進文本是代碼塊的指示。

簡單的解決方法是將該行替換為:

line = f"{line}\n"

如果你真的想要字符串文字,那么你可能要考慮使用textwrap.dedent function。

雖然,我會讓table成為一個列表,然后每行 append。 追加所有行后,然后join這些行。 事實上,您也可以對所有單元格執行相同的操作。 像這樣:

table = [
    f"|Rank|Title|Value|{"# words|" * n_words}{"Similarity|" * distance}",
    "|--|--|--|--|--|"
]
for i, el in enumerate(data):
    line = [f"{i + 1}", f'**{el["title"]}**', f'£{el["value"]:,}']
    if n_words:
        line.append(f'{str(el["n_words"])}')
    if distance:
        line.append(f'{str(round(el["distance"], 2))}')
    table.append(f'|{"|".join(line)}|')
st.markdown("\n".join(table))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM