# 使用vocabulary构建词典 Vocabulary 是包含字或词与index关系的类,用于将文本转换为index。 Args: max_size (int,可选):Vocab的最大大小,默认。 min_freq (int,可选):最小频率,默认。无 padding (str): padding令牌,默认为 pad。 unknown (str):未知标记,默认为 unk。 ## 构建Vocabulary ``` vocab = Vocabulary() word_list = "this is a word list".split() vocab.update(word_list) # 根据列表中的词更新词频 vocab.build_vocab() # 根据词频构建词典 print(vocab["word"]) # 5 print(vocab.to_word(5)) # `word` ``` ## 使用pd.Series构建Vocabulary ``` word_list_series = pd.Series([word_list]) # ['this', 'is', 'a', 'word', 'list'] idx_list_series = vocab.word_to_idx(word_list_series) print(idx_list_series) # [2,3,4,5,6] word_list_series = vocab.idx_to_word(idx_list_series) print(word_list_series) # ['this', 'is', 'a', 'word', 'list'] ``` ## 从pandas.DataFram中构建Vocabulary ``` word_list_dataFrame = pd.DataFrame({"text": [word_list]}) vocab = Vocabulary.from_dataset(word_list_dataFrame, field_name='text') ``` ## 读取文件进行初始化 ``` vocab = Vocabulary.from_file('./1.txt') ```