2017年11月1日 星期三

Jupyter notebook 操作(3) --- 程式碼存檔、查詢、重新載入

在 Jupyter notebook 上,如果想將打好的程式碼輸出成 .py 給別人使用、或要載入別人給 .py,應該怎麼做呢?
將以下程式碼儲存成 Crawler.py。
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

res = requests.get("http://www.taifex.com.tw/chinese/9/9_7_1.asp")
res.encoding='utf-8'
soup = bs(res.text, "lxml")
tb = soup.select(".table_c")[0]
df = pd.read_html(tb.prettify("utf-8"), encoding="utf-8", header = 0, index_col = 0)
df[0].columns = ('ID', 'Name', 'weight', 'No1', 'ID1', 'Name1', 'weight1')
df2 = df[0][[ 'ID', 'Name', 'weight']]
df2.head(100)

輸入以下指令
%save Crawler.py 5

查詢 Crawler.py 內容。
輸入以下指令,windows 請輸入 !type、Mac、Ubuntu、Linux 請輸入 !cat
!type Crawler.py

載入 Crawler.py 內容。
輸入以下指令
%load Crawler.py

shift + enter 執行。

參考資料: