python2.7练习小例子(十六)

    16):题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

    程序分析:利用 while 或 for 语句,条件为输入的字符不为 '\n'。

    程序源代码:

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import string
s = raw_input('请输入一个字符串:\n')
letters = 0
space = 0
digit = 0
others = 0
i=0
while i < len(s):
    c = s[i]
    i += 1
    if c.isalpha():
        letters += 1
    elif c.isspace():
        space += 1
    elif c.isdigit():
        digit += 1
    else:
        others += 1
print 'char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others)

    


#!/usr/bin/python
# -*- coding: UTF-8 -*-

import string
s = raw_input('请输入一个字符串:\n')
letters = 0
space = 0
digit = 0
others = 0
for c in s:
    if c.isalpha():
        letters += 1
    elif c.isspace():
        space += 1
    elif c.isdigit():
        digit += 1
    else:
        others += 1
print 'char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others)

    以上实例输出结果为:

 

请输入一个字符串:
123runoobc  kdf235*(dfl
char = 13,space = 2,digit = 6,others = 2

    Python3 下参考方案(可使用中文作为变量):

 

#!/usr/bin/python3

a = input('请输入一串字符:')
英文 = 0
空格= 0
数字= 0
其他= 0
for i in a:
    if i.isalpha():
        英文 += 1
    elif i.isspace():
        空格 += 1
    elif i.isnumeric():
        数字 += 1
    else:
        其他 += 1
print('英文 = %s,空格 = %s,数字 = %s,其他 = %s' % (英文,空格,数字,其他))

    Python3 下测试:

 

#!/usr/bin/env python3

InPut = input('输入任意字符:')
letters = []
spaces = []
digits = []
others = []
for i in iter(InPut):
    if i.isalpha() == True:
        letters.append(i)
    elif i.isspace() == True:
        spaces.append(i)
    elif i.isdigit() == True:
        digits.append(i)
    else:
        others.append(i)
print('''
字母: {}, 个数: {};
空字符: {}, 个数: {};
数字: {}, 个数: {};
其他: {}, 个数: {}'''.format(letters, len(letters), spaces, len(spaces), digits, len(digits), others, len(others)))

    使用正则表达式来计算(无法统计中文,要统计中文可以参考下面的例子):

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import re

def splitFunc():
    tmpStr = raw_input("输入字符串:")
    charNum  = 0
    digNum = 0
    spaceNum=0
    otherNum =0
    for i in range(len(tmpStr)):
        if re.match('\d',tmpStr[i]):
            digNum +=1
        elif re.match('[a-zA-Z]',tmpStr[i]):
            charNum +=1
        elif re.match('\s',tmpStr[i]):
            spaceNum +=1
        else:
            otherNum +=1
    print "字符:",charNum
    print "数字:",digNum
    print "空格:",spaceNum
    print "其他:",otherNum
splitFunc()

    

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import  re
str=raw_input('请输入一串字符:')

r1=re.compile('[a-zA-Z]')
r2=re.compile('[0-9]')
print '英文字母的个数为: %d' %len(re.findall(r1,str))
print '数字的个数为: %d' %len(re.findall(r2,str))
print '空格的个数为: %d' %len(re.findall(' ',str))
print '其他字符的个数为: %d' %(len(str)-len(re.findall(r1,str))-len(re.findall(r2,str))-len(re.findall(' ',str)))

    python3 参考方法:

 

#!/usr/bin/env python3

a = str(input("输入一行字符:"))
count1 = 0  #统计英文字母个数
count2 = 0  #统计数字个数
count3 = 0  #统计空格个数
count4 = 0  #统计其他字符
for i in range(len(a)):   #利用字符在ASCII码中的位置逐个统计
    if("0" <= a[i] <= "9"):
        count2 += 1
    elif("A" <= a[i] <= "Z" or "a" <= a[i] <= "z"):
        count1 += 1
    elif(a[i] == " "):
        count3 += 1
count4 = len(a) - count1 - count2 - count3
print("英文字母有%d个\n数字有%d个\n空格有%d个\n其他字符有%d个\n"%(count1,count2,count3,count4))

    使用匿名函数 lambda:

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-

s = raw_input('请输入一个字符串:\n')
print "开始统计..."
list = [0, 0, 0, 0]
temp = [lambda i : 1 if (i.isalpha()) else 0, lambda i : 1 if (i.isspace()) else 0, lambda i : 1 if (i.isdigit()) else 0]
for i in s:
    list[0] += temp[0](i)    # 字母
    list[1] += temp[1](i)    # 空格
    list[2] += temp[2](i)    # 数字
    list[3] = len(s) - list[0] - list[1] - list[2]  # 特殊字符

print list

    用 decode() 解码可以统计中文个数,utf-8 下一个中文占 3 位:

 

# encoding:utf-8

import re

'''因为中文字符占用长度不是1,用len()方法无法识别中文个数
'''
#答案方法
str = raw_input('请输入一行字符:')
str = str.decode('utf-8') # 解码成 unicode 类型,在 unicode 类型中,汉字占一位
word = 0
num = 0
space = 0
other = 0
for i in str:
    if re.match(r'\d', i):
        num += 1
    elif re.match(r'\w', i) and not re.match(r'\d', i):
        word += 1
    elif re.match(' ', i):
        space += 1
    else:
        other += 1
print '字母个数为:', word
print '数字个数为:', num
print '空格个数为:', space
print '其他字符个数:', other

    Python3 测试,可以统计中文:

 

#!/usr/bin/python3

#输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
#不能有效区分汉字。。。好像没有特定识别汉字的通用表达\s这样的#4E00~9FFFh 是中文的数字区域
import re
s = input('输入一串字符:')
char = re.findall(r'[a-zA-Z]',s)
num = re.findall(r'[0-9]',s)
blank = re.findall(r' ',s)
chi = re.findall(r'[\u4E00-\u9FFF]',s)
other = len(s)-len(char)-len(num)-len(blank)-len(chi)
print("字母:", len(char),"\n数字:", len(num),"\n空格:",len(blank),"\n中文:",len(chi),"\n其他:",other)

    

#!/usr/bin/env python
# -*- coding:utf-8 -*-

s ='12 3 45 & *?.;hGGK L67890'

dic = {'letter':0,'integer':0,'space':0,'other':0}
for i in s:
    if i>'a' and i<'z' or i>'A' and i<'Z':
        dic['letter'] += 1
    elif i in '0123456789':
        dic['integer'] += 1
    elif i == ' ':
        dic['space'] += 1
    else:
        dic['other'] += 1
print dic

    这个小例子就比较实用了,如果感觉不错的话,请多多点赞支持吧。。。

  原文链接:https://blog.csdn.net/luyaran/article/details/80050697

posted @ 2018-04-25 11:50  luyaran  阅读(487)  评论(0编辑  收藏  举报