Python3求英文文档中每个单词出现的次数并排序

[本文出自天外归云的博客园]

题目要求:

1、统计英文文档中每个单词出现的次数。

2、统计结果先按次数降序排序,再按单词首字母降序排序。

3、需要考虑大文件的读取。

我的解法如下:

import chardet
import re


# 大文件读取生成器
def read_big_file(f_path, chunk_size=100):
    f = open(f_path, 'rb')
    while True:
        # 每次读取指定内存大小的内容
        chunk_data = f.read(chunk_size)
        if not chunk_data:
            break
        # 获取文件编码并返回解码后的字符串
        detect = chardet.detect(chunk_data)
        # print(f'文件编码:{detect["encoding"]}')
        yield chunk_data.decode(detect["encoding"])


# Pythonic大文件读取生成器
def read_big_file_pythonic(f_path):
    with open(f_path, "rb") as f:
        for line in f.readlines():
            yield line.decode()


# 设定分词符并用字典统计单词出现次数
def words_freq(data, freq={}):
    for word in re.split('[,. ]', data):
        if word in freq:
            freq[word] += 1
        elif word != "":
            freq[word] = 1
    return freq


if __name__ == '__main__':
    f_path = "en_text.txt"
    freq = {}
    for i in read_big_file_pythonic(f_path):
        freq = words_freq(i, freq)
    print(sorted(freq.items(), key=lambda x: (x[1], x[0]), reverse=True))

其中read_big_file方法存在的问题:按大小进行文件读取可能会在边界处将一个单词拆分为两个单词,目前没找到什么好办法解决。

其中read_big_file_pythonic方法存在的问题:按行迭代读取,如果大文件只有一行就不好了。

所以要看实际情况合理选择两种方法的使用。

转载于:https://www.cnblogs.com/LanTianYou/p/9057172.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值