0023-python学习笔记:jieba库进行词频统计

0023-python学习笔记:jieba库进行词频统计,第1张

目录

一、jieba库

1.jieba.lcut():将完整句子严格分隔

2.jieba.lcut(s,cut_all=True):将句子可能的词语都分隔处理

3.jieba.add_word():添加新词

二、词频统计

1.英文词频统计

2.中文词频统计


一、jieba库 1.jieba.lcut():将完整句子严格分隔
import jieba
jieba.lcut("阳明先生于500年前开创心学这是对程朱理学的跨越对儒家精神的继承和发扬")

2.jieba.lcut(s,cut_all=True):将句子可能的词语都分隔处理 3.jieba.add_word():添加新词

二、词频统计 1.英文词频统计
def gettext():
    txt = open("ham.txt","r").read()
    txt = txt.lower()
    for ch in '!"#$%&*()_+,./:\<>?[]‘’~`':
        txt = txt.replace(ch,"")
    return txt
 
hamtxt = gettext()
words = hamtxt.split()
counts = {}
for word in words:
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key = lambda x:x[1],reverse=True)
for i in range(10):
    word,count = items[i]
    print("{0:<10}{1:>5}".format(word,count))
2.中文词频统计
import jieba
 
txt = open("sanguo.txt","r",encoding="utf-8").read()
excludes = {"将军","却说","二人","不可","荆州","不能","如此","军士","商议","如何","主公","左右","军马"}
words = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
    elif word == "诸葛亮" or word == "孔明曰":
        rword = "孔明"
    elif word == "关公" or word == "云长":
        rword = "关羽"
    elif word == "玄德" or word == "玄德曰":
        rword = "刘备"
    elif word == "孟德" or word == "丞相":
        rword = "曹 *** "
    else:
        rword = word
    counts[rword] = counts.get(rword,0) + 1
 
for word in excludes:
    del counts[word]
items = list(counts.items())
items.sort(key = lambda x:x[1],reverse=True)
 
 
for i in range(7):
    word,count = items[i]
    print("{0:<10}{1:>5}".format(word,count))

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/715997.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存