统计文件中大写字母和单词出现的次数educoder

dream.txt:

I have a dream that one day this nation will rise up and live out the true meaning of its creed: "we hold these truths to be self-evident, that all men are created equal." 

I have a Dream that one day on the red hills of Georgia, the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood. I have a Dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character. will

test.txt:

AAAA eeee BBB Cc ddd

 1.统计大写字母

#统计大写字母出现的次数,并按照字母出现次数降序排序输出
def countchar(file):
# *************begin************#
    txt=open(file,"r")#file本身就是一个字符串不用额外加双引号
    i=0
    count={}#定义一个空字典
    words=txt.read()#将文件内容读入(保存)到words中
    for word in words:#一个一个单词的读取words中的内容
        if word in count:#word在字典中
            count[word]+=1#字母word的值+1
        else:#word不在字典中
            if word>='A' and word<='Z':#第一次碰到大写字母
                count[word]=1#值置为1
    result=sorted(count.items(),key=lambda word:word[1],reverse=True)#遍历字典并降序排序
    for i in range(len(result)):#输出内容
        print(result[i])
    
# **************end*************#  


file = input()
countchar(file)

 2.统计单词

#统计一个文件中单词出现的次数,并输出出现次数最多的前3个单词
def countword(file):
    txt=open(file,"r")
    words=txt.read()
    for i in '",-:.':#将文本中的所有标点符号改为空格
        words=words.replace(i," ")
    words=words.split()#分隔单词
    count={}#定义一个空字典
    for word in words:
        count[word]=count.get(word,0)+1#对找到的单词值+1,否则为0
    result=sorted(count.items(),key=lambda word:word[1],reverse=True)#创建新列表以word值的大小降序排序
    for i in range (3):#输出出现次数最多的前三个单词
        print(result[i][::-1])

file = input()
countword(file)

猜你喜欢

转载自blog.csdn.net/weixin_61936651/article/details/123592829