Python 文本词频统计中英文

统计一段英文中 出现次数最多的几个单词

def get_text():
    text = open('eng.txt','r').read()
    text = text.lower() #所有单词都替换成小写
    for ch in '!@#$%^&*()_+-{}[]|\<>?/.,`~':#去噪,归一化处理,把所有特殊符号替换为空格
        text=text.replace(ch,"")
    return text

text=get_text()
ls = text.split(" ")
counts={}
for index,word in enumerate(ls):
    counts[word]=counts.get(word,0)+1
items=list(counts.items()) #字典转换为列表
items.sort(key=lambda x:x[1],reverse=True)#把列表按照键值对的第二个元素,由大到小排序
for i in range(5):#打印出现频率最高的5个词语
    word,fre = items[i]
    print (word,fre)

统计三国中出现次数最多的人名

import jieba
def get_text():
    text = open('threeking.txt', 'r', encoding="gb18030").read()
    return text
text = get_text()
ls = jieba.lcut(text)
#排除不需要统计的字符或词语
exclude=['将军','不可','二人','荆州','却说','不能','如此','商议','如何','主公','军士',
         '左右','军马','引兵','次日','大喜','天下','东吴','丞相','于是','今日','不敢','陛下','魏兵']
counts = {} #用来计数的集合

for word in ls: 
    if len(word) == 1: #排除掉长度为1的字或标点符号
        continue
    elif word in exclude:
        continue
    #对以下词语进行合并计算
    elif word == '玄德' or word == '玄德曰':
        rword = '刘备'
    elif word == '诸葛亮' or word == '孔明曰':
        rword = '孔明'
    elif word == '关公' or word == '云长':
        rword = '关羽'
    elif word == '都督':
        rword = '周瑜'
    elif word == '孟德':
        rword = '曹操'
    else:
        rword = word
    counts[rword] = counts.get(rword, 0)+1
items = list(counts.items()) #字典转换为列表
items.sort(key=lambda x: x[1], reverse=True)  #把列表按照键值对的第二个元素,由大到小排序
for i in range(10):#打印出现频率最高的词语
    word, fre = items[i]
    print(word, fre)

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值