用python写程序实现:输入一字符串,分别统计其中的英文字母个数,空格、数字和其他字符。

如题所述

第1个回答  2021-06-18
wz="计量单位是指根据约定定义和采用的标量,任何其他同类量可与其比较使两个量之比用一个数表示。计量单位具有根据约定赋予的名称和符号。"
for i in wz:
print("%s出现:%d次"%(i,wz.count(i)))
第2个回答  2015-01-14

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

本回答被网友采纳
第3个回答  2015-01-14
python中有些内置函数很逆天的。
第4个回答  2015-01-15
有内置函数的
第5个回答  2015-01-15
判断ascii码应该就可以了、、
相似回答