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

導(dǎo)入 ipywidgets 模塊
首先,你需要導(dǎo)入一堆東西,比如 ipywidgets 和 Twisted。Twisted 模塊可以用來創(chuàng)建一個(gè)異步時(shí)間計(jì)數(shù)器:
import twisted.internet.asyncioreactor
twisted.internet.asyncioreactor.install()
from twisted.internet import reactor, task
import ipywidgets, datetime, subprocess, functools, os
設(shè)置定時(shí)條目
用 Twisted 實(shí)現(xiàn)時(shí)間計(jì)數(shù)器是利用了 task.LoopingCall。然而,結(jié)束循環(huán)調(diào)用的唯一方法是用一個(gè)異常。倒計(jì)時(shí)時(shí)鐘總會(huì)停止,所以你需要一個(gè)自定義的異常來指示“一切正常;計(jì)數(shù)器結(jié)束”:
class DoneError(Exception):
pass
現(xiàn)在你已經(jīng)寫好了異常,你可以寫定時(shí)器了。第一步是創(chuàng)建一個(gè) ipywidgets.Label 的文本標(biāo)簽組件。循環(huán)使用 divmod 計(jì)算出分和秒,然后設(shè)置標(biāo)簽的文本值:
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 組件中保存文本
下一步是寫一些東西,將你輸入的文字保存到一個(gè)文件中,并提交到 Git。另外,由于你要寫 5 分鐘的日記,你需要一個(gè)能給你提供寫字區(qū)域的組件(滾動(dòng)肯定是可以的,但一次能看到更多的文字就更好了)。
這就用到了組件 Textarea,這是一個(gè)你可以書寫的文本字段,而 Output 則是用來給出反饋的。這一點(diǎn)很重要,因?yàn)?git push 可能會(huì)花點(diǎn)時(shí)間或失敗,這取決于網(wǎng)絡(luò)。如果備份失敗,用反饋提醒用戶很重要:
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 是為了避免每個(gè)字符都保存一遍并發(fā)送至 Git。相反,只要脫離輸入焦點(diǎn),它就會(huì)保存。這個(gè)函數(shù)也返回 save 函數(shù),所以可以明確地調(diào)用它。
創(chuàng)建一個(gè)布局
最后,你可以使用 ipywidgets.VBox 把這些東西放在一起。這是一個(gè)包含一些組件并垂直顯示的東西。還有一些其他的方法來排列組件,但這足夠簡單:
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!你已經(jīng)定義了一個(gè)寫日記的函數(shù)了,所以是時(shí)候試試了。
journal()
網(wǎng)站標(biāo)題:通過Jupyter撰寫日記
網(wǎng)站地址:http://m.fisionsoft.com.cn/article/dhojpie.html


咨詢
建站咨詢
