通过文本构建词典

# 获取单词出现频率
def word_count(file_name):
    import collections
    word_freq = collections.defaultdict(int)
    with open(file_name) as f:
        for l in f:
            for w in l.strip().split():
                word_freq[w] += 1
    return word_freq


def build_dict(file_name, min_word_freq=10):
    word_freq = word_count(file_name)  # 参见前一篇博客中的定义:https://blog.csdn.net/wiborgite/article/details/79870323
    word_freq = filter(lambda x: x[1] > min_word_freq, word_freq.items())  # filter将词频数量低于指定值的单词删除。
    word_freq_sorted = sorted(word_freq, key=lambda x: (-x[1], x[0]))
    # key用于指定排序的元素,因为sorted默认使用list中每个item的第一个元素从小到
    # 大排列,所以这里通过lambda进行前后元素调序,并对词频去相反数,从而将词频最大的排列在最前面
    words, _ = list(zip(*word_freq_sorted))
    
    # 单纯获取单词
    with open(r"data/voacb.txt",'a') as f:
        f.write('\n'.join(words))
        
    # 获取单词和单词比例
    #word_idx = dict(zip(words, range(len(words))))
    #word_idx['<unk>'] = len(words)  # unk表示unknown,未知单词
    #return word_idx

猜你喜欢

转载自blog.csdn.net/CSTGYinZong/article/details/127941102