1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 【Python】统计字符串中英文 空格 数字 标点个数

【Python】统计字符串中英文 空格 数字 标点个数

时间:2021-12-22 02:20:40

相关推荐

【Python】统计字符串中英文 空格 数字 标点个数

题外话:今天打酱油的做了网易数据挖掘工程师的在线笔试题,被打击了。

本文代码可在 这里 下载。

问题

在网上无意间看到这么一个题目:统计一个字符串中的中英文、空格、数字、标点符号个数。

正好再熟悉一下 Python 中字符串相关方法,所以来做一下。

代码

# coding: utf-8import stringfrom collections import namedtupledef str_count(s):'''找出字符串中的中英文、空格、数字、标点符号个数'''count_en = count_dg = count_sp = count_zh = count_pu = 0s_len = len(s)for c in s:if c in string.ascii_letters:count_en += 1elif c.isdigit():count_dg += 1elif c.isspace():count_sp += 1elif c.isalpha():count_zh += 1else:count_pu += 1total_chars = count_zh + count_en + count_sp + count_dg + count_puif 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 Nonereturn Nones = '上面是引用了官网的介绍,意思就是说 TensorBoard 就是一个方便你理解、调试、优化 TensorFlow 程序的可视化工具,你可以可视化你的 TensorFlow graph、学习参数以及其他数据比如图像。'count = str_count(s)print(s, end='\n\n')print('该字符串共有 {} 个字符,其中有 {} 个汉字,{} 个英文,{} 个空格,{} 个数字,{} 个标点符号。'.format(count.total, count.zh, count.en, count.space, count.digit, count.punc))

将上面的程序保存到str_count.py,然后执行测试下:

$ python str_count.py上面是引用了官网的介绍,意思就是说 TensorBoard 就是一个方便你理解、调试、优化 TensorFlow 程序的可视化工具,你可以可视化你的 TensorFlow graph、学习参数以及其他数据比如图像。该字符串共有 107 个字符,其中有 59 个汉字,36 个英文,6 个空格,0 个数字,6 个标点符号。

那个用于测试的字符串s源自 我的一篇关于 TensorBoard 的博文,首先输出原始字符串,然后输出中英文、空格、数字、标点符号各自的个数。

以后有好的想法再来优化这个程序,大家有什么好的想法也欢迎可以在评论区留言。

END

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。