分享一個2022年火遍全網的Python框架

cda數據分析師 發佈 2022-05-18T13:04:19.179712+00:00

作者:俊欣來源:關於數據分析與可視化最近Python圈子當中出來一個非常火爆的框架PyScript,該框架可以在瀏覽器中運行Python程序,只需要在HTML程序中添加一些Python代碼即可實現。

作者:俊欣

來源:關於數據分析與可視化

最近Python圈子當中出來一個非常火爆的框架PyScript,該框架可以在瀏覽器中運行Python程序,只需要在HTML程序中添加一些Python代碼即可實現。該項目出來之後便引起了轟動,馬上躥升到了Github趨勢榜榜首,短短20天已經有10K+的star了。既然如此,小編今天就帶大家來看看該框架是如何使用的。

HelloWorld

我們先來看一下簡單的例子,代碼如下

<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  </head>
  <body> <py-script> print('Hello, World!') </py-script> </body>
</html>

其中Python代碼被包裹在了py-script標籤裡面,然後我們在瀏覽器中查看出來的結果,如下所示

要不來畫個圖

下面這一個例子當中,我們嘗試將matplotlib繪製圖表的代碼放置到HTML代碼當中去,以實現繪製出一張直方圖的操作。首先是matplotlib代碼部分,

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
## 隨機生成滿足正態分布的隨機數據
rv = np.random.standard_normal(1000)

fig, ax = plt.subplots()
ax.hist(rv, bins=30)

output

然後我們將上面的代碼放置到HTML代碼當中去,代碼如下

<html>
<head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css"/>
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <py-env>
        - numpy
        - matplotlib
    </py-env>
</head>

<body>
<h1>Plotting a histogram of Standard Normal distribution</h1>
<div id="plot"></div>
<py-script output="plot">
    import matplotlib.pyplot as plt
    import numpy as np
    np.random.seed(42)
    rv = np.random.standard_normal(1000)
    fig, ax = plt.subplots()
    ax.hist(rv, bins=30)
    fig
</py-script>
</body>
</html>

output

由於我們後面需要用到numpymatplotlib兩個庫,因此我們通過py-env標籤來引進它們,另外

再畫個折線圖

我們在上面的基礎之上,再來繪製一張折線圖,首先我們再創建一個div標籤,裡面的idlineplot,代碼如下

<div id="lineplot"></div>

同樣地在py-script標籤中放置繪製折線圖的代碼,output對應div標籤中的id

<py-script output="lineplot">
.........
</py-script>

繪製折線圖的代碼如下

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

year1 = [2016, 2017, 2018, 2019, 2020]
population1 = [30, 46, 45, 55, 48]
year2 = [2016, 2017, 2018, 2019, 2020]
population2 = [43, 48, 44, 75, 45]

plt.plot(year1, population1, marker='o', linestyle='--', color='g', label='Countr_1')
plt.plot(year2, population2, marker='d', linestyle='-', color='r', label='Country_2')

plt.xlabel('Year')
plt.ylabel('Population (M)')
plt.title('Year vs Population')
plt.legend(loc='lower right')
fig

output

現階段運行帶有Pyscript的頁面加載速度並不會特別地快,該框架剛剛推出,仍然處於測試的階段,後面肯定會不斷地優化。要是遇到加載速度慢地問題,讀者朋友看一下是不是可以通過更換瀏覽器得以解決。

關鍵字: