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方法存在的问题:按行迭代读取,如果大文件只有一行就不好了。

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

posted @ 2018-05-18 17:33  天外归云  阅读(1909)  评论(0编辑  收藏  举报