python實踐:統計一個文本中單詞頻次最高的10個單詞?

#統計一個文本中單詞頻次最高的10個單詞?
import re
class Solution():
    def MaxWord(self,file_name):
        """
        :param file_name: 文件名
        :return:
        """
        with open(file_name,'r') as file:
            for lines in file:
                lines=re.sub('\W+',' ',lines)
            print(lines)
            dict_word={}
            for i in range(0,len(lines.split(' '))):
                word=lines.split(' ')[i]
                if word not in dict_word:
                    dict_word[word]=1
                else:
                    dict_word[word]+=1
            word_sorted=sorted(dict_word.items(),key=lambda x:x[1],reverse=True)
            for i in range(0,10):
                print(word_sorted[i])

if __name__=='__main__':
    solution=Solution()
    file_name='E:\python_test\exercise0406\information.txt'
    solution.MaxWord(file_name)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章