文本词频统计

文本词频统计

词频:单词出现的次数

# 统计英文:
f = open('F:\实习\python\hamlet','r',encoding='utf8')
data = f.read().lower()
data_split = data.split(' ')

count_dict = {}
for word in data_split:
    if word not in count_dict:
        count_dict[word] = 1
    else:
        count_dict[word] += 1

def func(i):
    return i[1]
lt = list(count_dict.items())
lt.sort(key = func)

lt.reverse()            # 运行结果由大到小排列
for i in lt[0:10]:
    print(f'{i[0]:^7}{i[1]^5}')
# 统计中文:
import jieba            # 导入一个jieba库,用来分词
f = open(r'F:\实习\python\0719\threekingdoms','r',encoding='utf8')
data = f.read()
data_jieba = jieba.lcut(data)

count_dict = {}
for word in data_jieba:
    if len(word) == 1:
        continue
    if word in {"将军", "却说", "荆州", "二人", "不可", "不能", "如此"}:
        continue
    if '曰' in word:
        word = word.replace('曰','')
    if word not in count_dict:
        count_dict[word] = 1
    else:
        count_dict[word] += 1

def func(i):
    return i[1]
data_list = list(count_dict.items())
data_list.sort(key = func)

data_list.reverse()
print(data_list)

转载于:https://www.cnblogs.com/yushan1/p/11213414.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值