import io


def _load_vectors(filename, head_n=None, open_encoding='utf-8'):
    """
    装载前N个词向量
    :param filename:
    :param head_n: head n word vectors will be loaded
    :return: dict, {word: str => vector: float list}
    """
    line_count = 0
    data = {}
    try:
        fin = io.open(filename, 'r', encoding=open_encoding,
                      newline='\n', errors='ignore')
    except FileNotFoundError as error:
        print(error)
        return data

    for line in fin:
        # load head n word vectors
        if head_n and head_n.__class__ == int:
            line_count += 1
            if line_count > head_n:
                break
        tokens = line.rstrip().replace('\n', '').split(' ')
        # map是一个类，Python中的高阶函数，类似于Scala中的array.map(func)
        # 将传入的函数作用于传入的可迭代对象（例如list）的每一个元素之上
        # float也是一个类
        # Convert a string or number to a floating point number, if possible.
        data[tokens[0]] = map(float, tokens[1:])
    fin.close()
    return data