新聞中心
Jupyter Notebook是一個開源的Web應用程序,允許用戶創(chuàng)建和共享包含代碼、方程式、可視化和文本的文檔。它的用途包括:數據清理和轉換、數值模擬、統(tǒng)計建模、數據可視化、機器學習等等。

導入 ipywidgets 模塊
首先,你需要導入一堆東西,比如 ipywidgets 和 Twisted。Twisted 模塊可以用來創(chuàng)建一個異步時間計數器:
import twisted.internet.asyncioreactor
twisted.internet.asyncioreactor.install()
from twisted.internet import reactor, task
import ipywidgets, datetime, subprocess, functools, os
設置定時條目
用 Twisted 實現(xiàn)時間計數器是利用了 task.LoopingCall。然而,結束循環(huán)調用的唯一方法是用一個異常。倒計時時鐘總會停止,所以你需要一個自定義的異常來指示“一切正常;計數器結束”:
class DoneError(Exception):
pass
現(xiàn)在你已經寫好了異常,你可以寫定時器了。第一步是創(chuàng)建一個 ipywidgets.Label 的文本標簽組件。循環(huán)使用 divmod 計算出分和秒,然后設置標簽的文本值:
def time_out_counter(reactor):
label = ipywidgets.Label("Time left: 5:00")
current_seconds = datetime.timedelta(minutes=5).total_seconds()
def decrement(count):
nonlocal current_seconds
current_seconds -= count
time_left = datetime.timedelta(seconds=max(current_seconds, 0))
minutes, left = divmod(time_left, minute)
seconds = int(left.total_seconds())
label.value = f"Time left: {minutes}:{seconds:02}"
if current_seconds "finished")
minute = datetime.timedelta(minutes=1)
call = task.LoopingCall.withCount(decrement)
call.reactor = reactor
d = call.start(1)
d.addErrback(lambda f: f.trap(DoneError))
return d, label
從 Jupyter 組件中保存文本
下一步是寫一些東西,將你輸入的文字保存到一個文件中,并提交到 Git。另外,由于你要寫 5 分鐘的日記,你需要一個能給你提供寫字區(qū)域的組件(滾動肯定是可以的,但一次能看到更多的文字就更好了)。
這就用到了組件 Textarea,這是一個你可以書寫的文本字段,而 Output 則是用來給出反饋的。這一點很重要,因為 git push 可能會花點時間或失敗,這取決于網絡。如果備份失敗,用反饋提醒用戶很重要:
def editor(fname):
textarea = ipywidgets.Textarea(continuous_update=False)
textarea.rows = 20
output = ipywidgets.Output()
runner = functools.partial(subprocess.run, capture_output=True, text=True, check=True)
def save(_ignored):
with output:
with open(fname, "w") as fpout:
fpout.write(textarea.value)
print("Sending...", end='')
try:
runner(["git", "add", fname])
runner(["git", "commit", "-m", f"updated {fname}"])
runner(["git", "push"])
except subprocess.CalledProcessError as exc:
print("Could not send")
print(exc.stdout)
print(exc.stderr)
else:
print("Done")
textarea.observe(save, names="value")
return textarea, output, save
continuous_update=False 是為了避免每個字符都保存一遍并發(fā)送至 Git。相反,只要脫離輸入焦點,它就會保存。這個函數也返回 save 函數,所以可以明確地調用它。
創(chuàng)建一個布局
最后,你可以使用 ipywidgets.VBox 把這些東西放在一起。這是一個包含一些組件并垂直顯示的東西。還有一些其他的方法來排列組件,但這足夠簡單:
def journal():
date = str(datetime.date.today())
title = f"Log: Startdate {date}"
filename = os.path.join(f"{date}.txt")
d, clock = time_out_counter(reactor)
textarea, output, save = editor(filename)
box = ipywidgets.VBox([
ipywidgets.Label(title),
textarea,
clock,
output
])
d.addCallback(save)
return box
biu!你已經定義了一個寫日記的函數了,所以是時候試試了。
journal()
分享名稱:通過Jupyter撰寫日記
分享URL:http://www.dlmjj.cn/article/dhojpie.html


咨詢
建站咨詢
