開始使用免費開始

熟悉文字資料

在這個練習中,你會透過分析《宅男行不行》(The Big Bang Theory)中 Sheldon Cooper 的台詞來玩玩文字資料。這能讓你練習如何分析句子,進而了解在真實情境中處理文字資料是怎麼一回事。

你會使用字典生成式來建立「字到索引」以及「索引到字」的對應字典。這裡選擇用字典,而不是例如 pandas.DataFrame,是因為字典更直覺,也不會引入不必要的額外複雜度。

資料已放在 sheldon_quotes,前兩個句子已經幫你列印出來了。

本練習屬於課程

使用 Keras 建立語言模型的循環神經網路(RNN)

檢視課程

練習說明

  • 將所有句子 join 成一個變數,接著擷取所有單字並存成串列 all_words
  • 對單字串列套用 list(set()) 以移除重複,並將結果存為 unique_words
  • 使用字典生成式,建立一個以索引為鍵、單字為值的字典。
  • 使用字典生成式,建立一個以單字為鍵、索引為值的字典。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Transform the list of sentences into a list of words
all_words = ' '.____(sheldon_quotes).split(' ')

# Get number of unique words
unique_words = list(set(all_words))

# Dictionary of indexes as keys and words as values
index_to_word = {____ for i, wd in enumerate(sorted(unique_words))}

print(index_to_word)

# Dictionary of words as keys and indexes as values
word_to_index = {wd:i for ____ in enumerate(sorted(unique_words))}

print(word_to_index)
編輯並執行程式碼