网络编程
位置:首页>> 网络编程>> Python编程>> Python实现统计文本中的字符数量

Python实现统计文本中的字符数量

作者:Python  发布时间:2021-01-28 00:27:04 

标签:Python,统计,字符

最近,由于工作需要统计一下文本文档中的各种不同类字符的数量。将txt文本文档中包含的的中文、英文、数字等字符数量进行统计。

这当然可以使用python的自动化来完成操作,其实采用python字符串自带的大多数函数就能够完成功能。

由于统计英文字符的需要,这里需要导入string内置模块,以及os等文件操作模块就能够轻松完成。

import string  # string内置模块
import os  # os文件操作模块

首先,需要开发一个函数用来完成对一个普通的字符串中的各种不同类型的字符进行统计,如下代码所示:

def count_string(str_=None):
    count_en = count_dg = count_sp = count_zh = count_pu = 0
    if str_ is None:
        print("字符串str_为空!")
        return count_en, count_dg, count_sp, count_zh, count_pu
    for st in str_:
        # 英文
        if st in string.ascii_letters:
            count_en += 1
        # 数字
        elif st.isdigit():
            count_dg += 1
        # 空格
        elif st.isspace():
            count_sp += 1
        # 中文
        elif st.isalpha():
            count_zh += 1
        # 特殊字符
        else:
            count_pu += 1
    print("字符串str_:", str_)
    return count_en, count_dg, count_sp, count_zh, count_pu

上面的count_string函数已经实现了可以对某个字符串中的不同字符数量进行统计。

接下来,需要读取我们的txt文本文档,然后对其中每一行的字符串进行统计。从而可以获取整个文档中的不同字符的数量分别是多少。

代码如下:

def read_text(text_path=None):
    count_en_all = count_dg_all = count_sp_all = count_zh_all = count_pu_all = 0
    if text_path is None:
        print('文本文档的路径不能为空!')
        return

    if not os.path.isfile(text_path):
        print('文本文档的路径不存在,请重新输入!')
        return

    with open(text_path, 'r', encoding='utf-8') as file_:
        for line_ in file_.readlines():
            if line_.strip() != '':
                count_en, count_dg, count_sp, count_zh, count_pu = count_string(line_)
                count_en_all = count_en_all + count_en
                count_dg_all = count_dg_all + count_dg
                count_sp_all = count_sp_all + count_sp
                count_zh_all = count_zh_all + count_zh
                count_pu_all = count_pu_all + count_pu

    print('当前文本文档{},结果统计如下:'.format(text_path))
    print('英文字符:', count_en_all)
    print('数字:', count_dg_all)
    print('空格:', count_sp_all)
    print('中文:', count_zh_all)
    print('特殊字符:', count_pu_all)

最后,我们通过调用read_text文本文档处理函数,即可统计出当前文档所有的不同字符的数量。

read_text('D:/test-data-work/data.txt')

# 当前文本文档D:/test-data-work/data.txt,结果统计如下:
# 英文字符:108
# 数字:209
# 空格:53
# 中文:288
# 特殊字符:90

若是需要批量操作,则可以使用python遍历文件夹的方式,对每个文档进行逐一统计。

这里可以使用os.listdir函数对文件夹进行简单的遍历操作。

for file_name in os.listdir('dir_path'):
    pass

来源:https://mp.weixin.qq.com/s/zifoO0kXga472n4J61XNsg

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com