python代码:计算一个文本文件中所有大写字母,小写字母,数字和其他的数量。

并以字典的形式返回结果

1、创建python代码,testread()file.py;

2、编写python代码,

import re

def getFileContent(str):

    str_value = str

    len_str_value = len(str_value)

    print(str_value)

    print(len_str_value)

    len_capital = len(re.compile(r'[A-Z]').findall(str_value))

    print(u'大写字母有%d个'%len_capital)

    len_lowercase = len(re.compile(r'[a-z]').findall(str_value))

    print(u'小写字母有%d个'%len_lowercase)

    len_num = len(re.compile(r'\d').findall(str_value))

    print(u'数字有%d个'%len_num)

    len_others = len_str_value -len_capital-len_lowercase-len_num

    print(u'其他的字符有%d个'%len_others)

    dict1 = {'capital':len_capital,'lowercase':len_lowercase,'others':len_others,'num':len_num}

    return dict1


if __name__ == '__main__':

    str = open('D:\\test.txt','r',encoding='UTF-8').read().replace('\t','').replace('\n','').replace(' ','').replace('space','')

    print(getFileContent(str))

3、右击‘在终端中运行Python文件’;

4、查看运行结果,满足需求;

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-11-10
#coding:utf-8
import re
def test(str_1):
    str1 = str_1
    len_str1 = len(str1)
    print len_str1
    len_capital = len(re.compile(r'[A-Z]').findall(str1))
    print u'大写字母有%d个'%len_capital
    len_lowercase = len(re.compile(r'[a-z]').findall(str1))
    print u'小写字母有%d个'%len_lowercase
    len_num = len(re.compile(r'\d').findall(str1))
    print u'数字有%d个'%len_num
    len_others = len_str1 -len_capital-len_lowercase-len_num
    print u'其他的字符有%d个'%len_others
    dict1 = {'capital':len_capital,'lowercase':len_lowercase,'others':len_others,'num':len_num}
    return dict1
if __name__ == '__main__':
    str_1 = open('c:\\test1.txt','r').read().replace('\t','').replace('\n','').replace(' ','').replace('space','')
    print test(str_1)

 

本回答被提问者和网友采纳
第2个回答  推荐于2018-03-01
>>> from collections import Counter
>>> c = Counter()
>>> for ch in 'programming':
...     c[ch] = c[ch] + 1
...
>>> c
Counter({'g': 2, 'm': 2, 'r': 2, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'p': 1})

第3个回答  2018-04-10
这是我用python3写的,字典老师还没讲……
a=input()
b="abcdefghigklmnopqrstuvwxyz"
m="0123456789"
c=str.upper(b)
d=0
e=0
n=0
q=0
h=0
z=len(a)
for i in range(z):
    if a[i] in b:
        d=d+1
    elif a[i] in c:
        e=e+1
    elif a[i] in m:
        n=n+1
    elif a[i] in " ":
        q=q+1
    else:
        h=h+1
print(d,e,n,q,h)

相似回答