如何用python对文章中文分词并统计词频

Python030

如何用python对文章中文分词并统计词频,第1张

1、全局变量在函数中使用时需要加入global声明

2、获取网页内容存入文件时的编码为ascii进行正则匹配时需要decode为GB2312,当匹配到的中文写入文件时需要encode成GB2312写入文件。

3、中文字符匹配过滤正则表达式为ur'[\u4e00-\u9fa5]+',使用findall找到所有的中文字符存入分组

4、KEY,Value值可以使用dict存储,排序后可以使用list存储

5、字符串处理使用split分割,然后使用index截取字符串,判断哪些是名词和动词

6、命令行使用需要导入os,os.system(cmd)

 #! 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)