加入特殊權杖
你現在要學習在句子中加入 sos(開頭標記)與 eos(結尾標記)權杖。前面提過,以你目前的模型來說這一步是可選的,不過在之後章節要實作的模型就會需要這些標記。
要加入這些特殊權杖,你會使用 Python 的 string.join() 函式。string.join() 會用分隔符號把字串清單接成單一字串。例如,若要把 ['datacamp', 'is', 'awesome'] 轉成 'datacamp is awesome',你可以使用 " ".join(['datacamp', 'is', 'awesome']),其中的 " "(也就是空白字元)就是分隔符號。
在這個練習中,已經匯入了一個包含 10 句法文句子的簡小範例。
本練習屬於課程
使用 Keras 進行機器翻譯
練習說明
- 逐一走訪法文句子的清單(
fr_text)。 - 使用
string.join()函式,為每個句子在開頭加上"sos"權杖,並在結尾加上"eos"權杖。 - 將修改後的句子加入
fr_text_new。 - 列印修改後的句子
sent_new。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
fr_text_new = []
# Loop through all sentences in fr_text
for sent in ____:
print("Before adding tokens: ", sent)
# Add sos and eos tokens using string.join
sent_new = " ".____([____, sent, ____])
# Append the modified sentence to fr_text_new
____.____(____)
# Print sentence after adding tokens
print("After adding tokens: ", ____, '\n')