Python统计字符串中的中英文字符、数字空格,特殊字符

 

 

# -*- coding:utf8 -*-
import string
from collections import namedtuple

def str_count(s):
    '''找出字符串中的中英文、空格、数字、标点符号个数'''
    count_en = count_dg = count_sp = count_zh = count_pu = 0

    s_len = len(s)
    for c in s:
        # 英文
        if c in string.ascii_letters:
            count_en += 1
        # 数字
        elif c.isdigit():
            count_dg += 1
        # 空格
        elif c.isspace():
            count_sp += 1
        # 中文
        elif c.isalpha():
            count_zh += 1
        # 特殊字符
        else:
            count_pu += 1

    total_chars = count_zh + count_en + count_sp + count_dg + count_pu
    if total_chars == s_len:
        return namedtuple('Count', ['total', 'zh', 'en', 'space', 'digit', 'punc'])(s_len, count_zh, count_en,count_sp, count_dg, count_pu)
    else:
        print('Something is wrong!')
        return None

if __name__ == '__main__':
    str_l = "这是一个test字符串"
    count = str_count(str_l)
    print(str_l, end='\n\n')
    print('该字符串共有 {} 个字符,其中有 {} 个汉字,{} 个英文,{} 个空格,{} 个数字,{} 个标点符号。'.format(count.total, count.zh, count.en, count.space,
                                                                           count.digit, count.punc))

 

转载于:https://www.cnblogs.com/zihe/p/8323508.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值