编程语言
首页 > 编程语言> > python37实现1-统计文本中出现次数最多的单词

python37实现1-统计文本中出现次数最多的单词

作者:互联网

#读取文本文件
with open(r"./article.txt","r") as ff:
    #创建空字典
    article_dic={}
    for line in ff:
        #去掉行尾换行字符
        words=line[:-1]
        #将每行按单词为成员放入列表中
        words=words.split()
        for word in words:
            #判断单词是否在字典中
            if word not in article_dic:
                #不存在则字典值置0
                article_dic[word]=0
            article_dic[word] += 1
    print(article_dic)
#将字典变为列表,列表成员为字典的键值对组成的元祖
list_article=article_dic.items()
#按照值(单词出现次数)进行排序
sorted_article=sorted(list_article,key=lambda x:x[1],reverse=True)
#打印排序后列表
print(sorted_article)

标签:word,dic,单词,python37,words,article,文本,字典
来源: https://www.cnblogs.com/ttmaoxianjun/p/14616313.html