基于jieba库实现中文词频统计
安装
python的工具,安装当然是使用pip安装了。
pip install jieba
使用
先看一个小例子,下面的代码是从一个文本文件中分词并统计出现频率最高的10个单词,并打印到控制台。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import jieba
import jieba.analyse
import codecs
import re
from collections import Counter
class WordCounter(object):
def count_from_file(self, file, top_limit=0):
with codecs.open(file, 'r', 'utf-8') as f:
content = f.read()
content = re.sub(r'\s+', r' ', content)
content = re.sub(r'\.+', r' ', content)
return self.count_from_str(content, top_limit=top_limit)
def count_from_str(self, content, top_limit=0):
if top_limit <= 0:
top_limit = 100
tags = jieba.analyse.extract_tags(content, topK=100)
words = jieba.cut(content)
counter = Counter()
for word in words:
if word in tags:
counter[word] += 1
return co