tf-idf算法python实现

Python014

tf-idf算法python实现,第1张

tf-idf=tf*idf

tf是词频,若一个文件中有n个次,词word出现c次;,则tf=c/n

idf是逆文档概率,一共有N个文件,词word在w个文档中出现,则idf=w/N

 #! python3

# -*- coding: utf-8 -*-

import os, codecs

import jieba

from collections import Counter

 

def get_words(txt):

    seg_list = jieba.cut(txt)

    c = Counter()

    for x in seg_list:

        if len(x)>1 and x != '\r\n':

            c[x] += 1

    print('常用词频度统计结果')

    for (k,v) in c.most_common(100):

        print('%s%s %s  %d' % ('  '*(5-len(k)), k, '*'*int(v/3), v))

 

if __name__ == '__main__':

    with codecs.open('19d.txt', 'r', 'utf8') as f:

        txt = f.read()

    get_words(txt)