import string
def chartype(ch):
if ch in string.ascii_letters: return 'ascii_letters'
elif ch in string.digits: return 'digits'
elif ch in string.whitespace: return 'whitespace'
else: return 'other'
def iterchtypecount(s):
counter = {}
for c in s:
counter.setdefault(chartype(c), []).append(c)
for t, lst in counter.items():
yield t, len(lst)
for chtype, cnts in iterchtypecount(raw_input("Enter a string: ")):
print chtype, cnts
追问能简单点吗,我刚开始学python,看不懂
追答# coding: utf-8
import string
def chartype(ch):
"""字符类型判断"""
if ch in string.ascii_letters: return 'ascii_letters'
elif ch in string.digits: return 'digits'
elif ch in string.whitespace: return 'whitespace'
else: return 'other'
def chtypecount(s):
"""字符串类型计数器"""
counter = {}
for ct in map(chartype, s):
counter.setdefault(ct, 0)
counter[ct] += 1
return counter
for chtype, cnts in chtypecount(raw_input("Enter a string: ")).items():
print chtype, cnts
本回答被网友采纳