[英]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)
出于某种原因,它适用于第一行,但不适用于任何其他行。 我在做什么明显错误的事情吗?
非常感谢!
你有两个问题。
markdown
的调用需要减少缩进,以便在 for 循环结束后调用它,而不是在第一个循环结束时调用。具体来说,这条线...
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.