No. 0004 Practice _python The number of words appearing in the statistics text

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.