MCPcopy Index your code
hub / github.com/tensorlayer/TensorLayer / initialize_vocabulary

Function initialize_vocabulary

tensorlayer/nlp.py:970–1013  ·  view source on GitHub ↗

Initialize vocabulary from file, return the `word_to_id` (dictionary) and `id_to_word` (list). We assume the vocabulary is stored one-item-per-line, so a file will result in a vocabulary {"dog": 0, "cat": 1}, and this function will also return the reversed-vocabulary ["dog", "cat"]. Pa

(vocabulary_path)

Source from the content-addressed store, hash-verified

968
969
970def initialize_vocabulary(vocabulary_path):
971 """Initialize vocabulary from file, return the `word_to_id` (dictionary)
972 and `id_to_word` (list).
973
974 We assume the vocabulary is stored one-item-per-line, so a file will result in a vocabulary {"dog": 0, "cat": 1}, and this function will also return the reversed-vocabulary ["dog", "cat"].
975
976 Parameters
977 -----------
978 vocabulary_path : str
979 Path to the file containing the vocabulary.
980
981 Returns
982 --------
983 vocab : dictionary
984 a dictionary that maps word to ID.
985 rev_vocab : list of int
986 a list that maps ID to word.
987
988 Examples
989 ---------
990 >>> Assume 'test' contains
991 dog
992 cat
993 bird
994 >>> vocab, rev_vocab = tl.nlp.initialize_vocabulary("test")
995 >>> print(vocab)
996 >>> {b'cat': 1, b'dog': 0, b'bird': 2}
997 >>> print(rev_vocab)
998 >>> [b'dog', b'cat', b'bird']
999
1000 Raises
1001 -------
1002 ValueError : if the provided vocabulary_path does not exist.
1003
1004 """
1005 if gfile.Exists(vocabulary_path):
1006 rev_vocab = []
1007 with gfile.GFile(vocabulary_path, mode="rb") as f:
1008 rev_vocab.extend(f.readlines())
1009 rev_vocab = [as_bytes(line.strip()) for line in rev_vocab]
1010 vocab = dict([(x, y) for (y, x) in enumerate(rev_vocab)])
1011 return vocab, rev_vocab
1012 else:
1013 raise ValueError("Vocabulary file %s not found.", vocabulary_path)
1014
1015
1016def sentence_to_token_ids(

Callers 1

data_to_token_idsFunction · 0.85

Calls 1

as_bytesFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…