Udacity Machine Learning course count words

Source: Internet
Author: User

"""Count words."""defCount_words (S, N):"""Return The n most frequently occuring words in S."""        #Todo:count The number of occurences of each word in SWord =s.split () worddict= {}     forIteminchWord:ifItem not inchWorddict:worddict[item]= 1Else: Worddict[item]+ = 1#Todo:sort the occurences in descending order (alphabetically in case of ties)Sortedworddict = sorted (Worddict.iteritems (), key =LambdaX: (-x[1],x[0]), reverse=False)#Todo:return the top n words as a list of tuples (<word>, <count>)Top_n = []     forIinchrange (N): Top_n.append (Sortedworddict[i])returnTop_ndefTest_run ():"""Test count_words () with some inputs."""    PrintCount_words ("Cat Bat Mat cat bat Cat", 3)    PrintCount_words ("Betty bought a bit of butter but the butter was bitter", 3)if __name__=='__main__': Test_run ()

Udacity Machine Learning course count words

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.