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!
如果您發現本教學有幫助,請不要忘記分享並訂閱更多內容。下一篇文章見!
如果您想支持我的寫作或請我喝杯啤酒:https://buymeacoffee.com/bmours
以上是Streamlit 部分寫入與文字元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python不是嚴格的逐行執行,而是基於解釋器的機制進行優化和條件執行。解釋器將代碼轉換為字節碼,由PVM執行,可能會預編譯常量表達式或優化循環。理解這些機制有助於優化代碼和提高效率。

可以使用多種方法在Python中連接兩個列表:1.使用 操作符,簡單但在大列表中效率低;2.使用extend方法,效率高但會修改原列表;3.使用 =操作符,兼具效率和可讀性;4.使用itertools.chain函數,內存效率高但需額外導入;5.使用列表解析,優雅但可能過於復雜。選擇方法應根據代碼上下文和需求。

有多種方法可以合併Python列表:1.使用 操作符,簡單但對大列表不內存高效;2.使用extend方法,內存高效但會修改原列表;3.使用itertools.chain,適用於大數據集;4.使用*操作符,一行代碼合併小到中型列表;5.使用numpy.concatenate,適用於大數據集和性能要求高的場景;6.使用append方法,適用於小列表但效率低。選擇方法時需考慮列表大小和應用場景。

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python中,for循環用於遍歷可迭代對象,while循環用於條件滿足時重複執行操作。 1)for循環示例:遍歷列表並打印元素。 2)while循環示例:猜數字遊戲,直到猜對為止。掌握循環原理和優化技巧可提高代碼效率和可靠性。

要將列表連接成字符串,Python中使用join()方法是最佳選擇。 1)使用join()方法將列表元素連接成字符串,如''.join(my_list)。 2)對於包含數字的列表,先用map(str,numbers)轉換為字符串再連接。 3)可以使用生成器表達式進行複雜格式化,如','.join(f'({fruit})'forfruitinfruits)。 4)處理混合數據類型時,使用map(str,mixed_list)確保所有元素可轉換為字符串。 5)對於大型列表,使用''.join(large_li

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

Dreamweaver CS6
視覺化網頁開發工具

記事本++7.3.1
好用且免費的程式碼編輯器