加载向量文件
(file_name)
| 26 | |
| 27 | |
| 28 | def load_vectors(file_name): |
| 29 | """ |
| 30 | 加载向量文件 |
| 31 | """ |
| 32 | print("begin load vectors") |
| 33 | |
| 34 | input_file = open(file_name, "rb") |
| 35 | |
| 36 | # 获取词表数目及向量维度 |
| 37 | words_and_size = input_file.readline() |
| 38 | words_and_size = words_and_size.strip() |
| 39 | words = int(words_and_size.decode('utf-8').split(' ')[0]) |
| 40 | size = int(words_and_size.decode('utf-8').split(' ')[1]) |
| 41 | print("words =", words) |
| 42 | print("size =", size) |
| 43 | |
| 44 | word_vector_dict = {} |
| 45 | word_id_dict = {} |
| 46 | |
| 47 | for word_id in range(0, words): |
| 48 | word = b'' |
| 49 | # 读取一个词 |
| 50 | while True: |
| 51 | charactor = input_file.read(1) |
| 52 | if charactor is False or charactor == b' ': |
| 53 | break |
| 54 | word = word + charactor |
| 55 | word = word.strip() |
| 56 | |
| 57 | # 读取词向量 |
| 58 | vector = np.empty([size]) |
| 59 | for index in range(0, size): |
| 60 | weight_str = input_file.read(FLOAT_SIZE) |
| 61 | (weight,) = struct.unpack('f', weight_str) |
| 62 | vector[index] = weight |
| 63 | |
| 64 | # 将词及其对应的向量存到dict中 |
| 65 | word_vector_dict[word] = vector |
| 66 | word_id_dict[word] = word_id |
| 67 | |
| 68 | input_file.close() |
| 69 | |
| 70 | print("load vectors finish") |
| 71 | return word_vector_dict, word_id_dict |
| 72 | |
| 73 | if __name__ == '__main__': |
| 74 | if len(sys.argv) != 2: |
no outgoing calls
no test coverage detected