Streamlit 部分写入和文本元素
Getting Started with Streamlit: A Beginner's Guide
Code can be found here: GitHub - jamesbmour/blog_tutorials:
Video version of blog can be found here: https://youtu.be/EQcqNW7Nw7M
Introduction
Streamlit is an open-source app framework that allows you to create beautiful, interactive web applications with minimal effort. If you’re a data scientist, machine learning engineer, or anyone working with data, Streamlit is the perfect tool to turn your Python scripts into interactive apps quickly. In this tutorial, we will dive into the basics of Streamlit by exploring some of its powerful features, such as st.write(), magic commands, and text elements.
Let’s get started by building a simple app to demonstrate these functionalities!
Setting Up Your Streamlit Environment
Before we jump into the code, make sure you have Streamlit installed. If you haven't installed it yet, you can do so with the following command:
pip install streamlit
Now, let’s start coding our first Streamlit app.
Building Your First Streamlit App
1. Adding a Title to Your App
Streamlit makes it incredibly easy to add titles and headings to your app. The st.title() function allows you to display a large title at the top of your application, which serves as the main heading.
import streamlit as st st.title("Introduction to Streamlit: Part 1")
This will display a large, bold title at the top of your app.
Streamlit Write Elements
Using st.write() for Versatile Output
The st.write() function is one of the most versatile functions in Streamlit. You can use it to display almost anything, including text, data frames, charts, and more—all with a single line of code.
Displaying a DataFrame
Let's start by displaying a simple DataFrame using st.write().
import pandas as pd df = pd.DataFrame({ "Column 1": [1, 2, 3, 4], "Column 2": [10, 20, 30, 40] }) st.write("DataFrame using st.write() function") st.write(df)
This code creates a DataFrame with two columns and displays it directly in your app. The beauty of st.write() is that it automatically formats the DataFrame into a neat table, complete with scroll bars if needed.
Displaying Markdown Text
Another cool feature of st.write() is its ability to render Markdown text. This allows you to add formatted text, such as headers, subheaders, and paragraphs, with ease.
markdown_txt = ( "### This is a Markdown Header\\n" "#### This is a Markdown Subheader\\n" "This is a Markdown paragraph.\\n" ) st.write(markdown_txt)
With just a few lines of code, you can add rich text to your app.
Streaming Data with st.write_stream()
Streamlit also allows you to stream data to your app in real-time using the st.write_stream() function. This is particularly useful for displaying data that updates over time, such as sensor readings or live analytics.
import time st.write("## Streaming Data using st.write_stream() function") stream_btn = st.button("Click Button to Stream Data") TEXT = """ # Stream a generator, iterable, or stream-like sequence to the app. """ def stream_data(txt="Hello, World!"): for word in txt.split(" "): yield word + " " time.sleep(0.01) if stream_btn: st.write_stream(stream_data(TEXT))
In this example, when the button is clicked, the app will start streaming data word by word from the TEXT string, simulating real-time data updates.
Streamlit Text Elements
In addition to data streaming, Streamlit provides several text elements to enhance the presentation of your app.
Headers and Subheaders
You can easily add headers and subheaders using st.header() and st.subheader():
st.header("This is a Header") st.subheader("This is a Subheader")
These functions help structure your content, making your app more organized and visually appealing.
Captions
Captions are useful for adding small notes or explanations. You can add them using st.caption():
st.caption("This is a caption")
Displaying Code
If you want to display code snippets in your app, you can use st.code():
code_txt = """ import pandas as pd import streamlit as st st.title("Streamlit Tutorials") for i in range(10): st.write(i) """ st.code(code_txt)
This will display the code in a nicely formatted, syntax-highlighted block.
Displaying Mathematical Expressions
For those who need to include mathematical equations, Streamlit supports LaTeX:
st.latex(r"e = mc^2") st.latex(r"\\int_a^b x^2 dx")
These commands will render LaTeX equations directly in your app.
Adding Dividers
To separate different sections of your app, you can use st.divider():
st.write("This is some text below the divider.") st.divider() st.write("This is some other text below the divider.")
Dividers add a horizontal line between sections, helping to break up the content visually.
Conclusion
In this introductory tutorial, we covered the basics of Streamlit, including how to use st.write() to display data and text, and how to stream data using st.write_stream(). We also explored various text elements to enhance the structure and readability of your app.
Streamlit makes it incredibly easy to create interactive web applications with just a few lines of code. Whether you're building dashboards, data exploration tools, or any other data-driven app, Streamlit provides the tools you need to get started quickly.
In the next tutorial, we’ll dive deeper into widgets and interactivity features in Streamlit. Stay tuned!
Wenn Sie dieses Tutorial hilfreich fanden, vergessen Sie nicht, es zu teilen und sich für weitere Inhalte zu abonnieren. Wir sehen uns im nächsten Beitrag!
Wenn Sie mein Schreiben unterstützen oder mich mit einem Bier verwöhnen möchten: https://buymeacoffee.com/bmours
以上是Streamlit 部分写入和文本元素的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。 Python以简洁和强大的生态系统着称,C 则以高性能和底层控制能力闻名。

2小时内可以学会Python的基本编程概念和技能。1.学习变量和数据类型,2.掌握控制流(条件语句和循环),3.理解函数的定义和使用,4.通过简单示例和代码片段快速上手Python编程。

Python在游戏和GUI开发中表现出色。1)游戏开发使用Pygame,提供绘图、音频等功能,适合创建2D游戏。2)GUI开发可选择Tkinter或PyQt,Tkinter简单易用,PyQt功能丰富,适合专业开发。

两小时内可以学到Python的基础知识。1.学习变量和数据类型,2.掌握控制结构如if语句和循环,3.了解函数的定义和使用。这些将帮助你开始编写简单的Python程序。

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

要在有限的时间内最大化学习Python的效率,可以使用Python的datetime、time和schedule模块。1.datetime模块用于记录和规划学习时间。2.time模块帮助设置学习和休息时间。3.schedule模块自动化安排每周学习任务。

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。
