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('该字符串共有 {} 个字符,其中有 {} 个汉字,{} 个英⽂,{} 个空格,{} 个数字,{} 个标点符号。'.al, count.zh, , count.space,
count.digit, count.punc))
namedtuple使⽤参考:
输出为:
该字符串共有 11 个字符,其中有 7 个汉字,4 个英⽂,0 个空格,0 个数字,0 个标点符号。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。