简体   繁体   English

Python - Markdown 表 - 在 Streamlit 中仅显示第一行

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

I can try and produce a reproducible example if need be, but thought I would show the code first.如果需要,我可以尝试生成一个可重现的示例,但我想我会先展示代码。 I am using Streamlit and a function which takes a JSON file and produces a table from it in markdown:我正在使用 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)

For some reason, it is working for the first row, but not for any other rows.出于某种原因,它适用于第一行,但不适用于任何其他行。 Am I doing anything which is obviously wrong?我在做什么明显错误的事情吗?

在此处输入图像描述

Many thanks!非常感谢!

You have two issues.你有两个问题。

  1. The call to markdown needs to be outdented so that it is called after the for loop ends, instead of at the end of the first cycle.markdown的调用需要减少缩进,以便在 for 循环结束后调用它,而不是在第一个循环结束时调用。
  2. You need to remove the indentation from your string literal.您需要从字符串文字中删除缩进。

Specifically, this line...具体来说,这条线...

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

... causes every line after the first one to be indented by 16 spaces. ...导致第一行之后的每一行缩进 16 个空格。 Of course, Markdown sees that indentation as an indication that the indented text is a code block.当然,Markdown 将缩进视为缩进文本是代码块的指示。

The simple fix would be to replace that line with:简单的解决方法是将该行替换为:

line = f"{line}\n"

If you really wanted the string literal, then you might want to consider making use of thetextwrap.dedent function.如果你真的想要字符串文字,那么你可能要考虑使用textwrap.dedent function。

Although, I would make table a list and then append each line.虽然,我会让table成为一个列表,然后每行 append。 After all of the lines are appended, then join the lines.追加所有行后,然后join这些行。 In fact, you could do the same for all the cells as well.事实上,您也可以对所有单元格执行相同的操作。 Like this:像这样:

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