熟悉文本数据
在本练习中,您将通过分析美剧 The Big Bang Theory 中 Sheldon Cooper 的台词来玩转文本数据。这将让您有机会分析句子,并了解处理真实世界文本数据时的特点与挑战。
您将使用字典推导式创建将单词映射到索引、以及将索引映射到单词的字典。这里选择使用字典,而不是例如 pandas.DataFrame,是因为字典更直观,也不会引入不必要的额外复杂性。
数据保存在 sheldon_quotes 中,前 2 个句子已为您打印出来。
本练习是课程的一部分
使用 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)