The No. 0004 question of Python exercises
Https://github.com/Show-Me-the-Code/show-me-the-code
Question No. 0004: Any plain text file in English, counting the number of occurrences of the word.
Talk was cheap, show you My Code.
#!/usr/bin/env python#!-*-coding:utf-8-*- fromCollectionsImportordereddict__author__ =' Sophie ' class appearancecounter(object): def __init__(self):Self.dict = {} def add_count(self,item):Count = Self.dict.setdefault (item,0) Self.dict[item] = count +1 def sort(self, desc = None): "" " ~~~~~~method 1~~~~~~~~~ " "" #result = sorted ([(V,k) for (k,v) in Self.dict.items ()], reverse = desc) "" " ~~~~~~method 2~~~~~~~~~ " ""result = Ordereddict (sorted (Self.dict.items (), key =Lambdax:x[1], reverse = desc))returnResultif__name__ = =' __main__ ': AC = appearancecounter () file = open ('/users/sophie/pycharmprojects/practice_0004/cnn_news.txt ',' R ')Try: List_of_all_lines = File.readlines ()finally: File.close () list_of_all_words = [] temp = [] forXinchList_of_all_lines:temp = [T.strip (".? \ "!, () '") forTinchX.lower (). Split ()] List_of_all_words.extend (temp) forXinchList_of_all_words:ac.add_count (x) r = Ac.sort (True)PrintR
Small knowledge Point get
1, SetDefault (key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. Default defaults to None.
This works well if key already exists in the dictionary, returns its corresponding value, and if key does not exist, insert key and default value
2, there are many key-value in my dictionary, how to sort?
Http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
No. 0004 Practice _python The number of words appearing in the statistics text