Python统计字符串中的中英文字符、数字空格,特殊字符
2024-10-18 08:30:53
# -*- 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))
最新文章
- CozyRSS开发记录15-获取和显示RSS内容
- 玩转JavaScript OOP[2]——类的实现
- 微信连WiFi expired timestamp 和sign错误小坑解决
- unity3d插件Daikon Forge GUI 中文教程2-基础控件Label的使用
- nginx配置文件注释
- paip.解决 数据库mysql增加列 字段很慢添加字段很慢
- js markdown chart flow
- 六、CCLayer
- php如何清除html格式并去除文字中的空格然后截取文字
- Eclipse / Android : “Errors running builder 'Android Pre Compiler' on project…”
- C语言之二维数组与指针
- memset memcmp memcpy memmove 自己实现
- Mudo C++网络库第十章学习笔记
- ";Native table 'performance_schema'.'session_variables' has the wrong structure";) [SQL: ";SHOW VARIABLES LIKE 'sql_mode'";]
- List排序Collections.sort 重写compare
- 『cs231n』通过代码理解gan网络&;tensorflow共享变量机制_上
- hadoop day 2
- Atitit 获取剪贴板内容
- PyQT5-QCalendarWidget 日历显示
- IDEA的强大
热门文章
- 几张图轻松理解String.intern()
- mybatis由浅入深day02_4多对多查询_多对多查询总结
- 使用select多选标签笔记
- Exception in thread ";main"; java.lang.NoSuchMethodError: org.testng.TestNG.configure(Lorg/testng/CommandLineArgs;)V
- ssh&;scp指定密钥
- 第六篇:GPU 并行优化的几种典型策略
- PHP创建文件以及移动文件
- PyQt4单选框QCheckBox
- Go基础---->;go的基础学习(二)
- ReactNative For Android 项目实战总结