import codecs


def complete_vocabulary(filename, initial_words, wordlength, vocsize, encoding="utf-8"):
    """
    Reads words of length <wordlength>, from <filename>, until the number_of_words_read+len(initial_words)=vocsize. Returns a dictionary of words and their frequency.

    :param filename: text file, without header, with "frequency word\n" format
    :param initial_words: dictionary with initial words:freq that have to be in the final selection
    :param wordlength: int, length of words we consider
    :param vocsize: vocabulary size to achieve
    :return: dictionary of words:frequency
    """
    wfs=initial_words.copy()

    with codecs.open(filename, encoding=encoding) as kf:
        nl = 0
        for line in kf:
            fields = line.split()
            if len(fields) != 2:
                raise Exception("File %s is not well formatted. I expected frequency word format."%filename)
            fr, w = fields[0].strip(),fields[1].strip()
            fr = int(fr)
            if len(w) == wordlength:
                if w in wfs.keys():
                    continue
                else:
                    wfs[w]=fr
                    if len(wfs) == vocsize:
                        return wfs
    return wfs