Python advanced to count the words in Python

Source: Internet
Author: User

Problem Description:

The function is implemented in Python count_words() , which enters s a string and n a number, returning the s n most frequently occurring word. The return value is a list of tuples that contain the most occurrences of the word and its number of occurrences, that is n [(<单词1>, <次数1>), (<单词2>, <次数2>), ... ] , in descending order of occurrences.

You can assume that all inputs are lowercase and do not contain punctuation marks or other characters (only letters and a single space). If they occur the same number of times, they are sorted alphabetically.

For example:

print count_words("betty bought a bit of butter but the butter was bitter",3)

Output:

[(‘butter‘, 2), (‘a‘, 1), (‘betty‘, 1)]

Problem-Solving ideas:

1. Divide the string s into blank characters to get all the word lists split_s, such as: [' Betty ', ' bought ', ' a ', ' bit ', ' of ', ' butter ', ' but ', ' the ', ' butter ', ' is ', ' bitter ' ]

2. Establish maplist and convert the split_s into elements as a list of tuples, such as: [(' Betty ', 1), (' bought ', 1), (' A ', 1), (' A ', 1), (' of ', 1), (' of ', "1 '), (' but '), 1), (' The ', 1), (' Butter ', 1), (' was ', 1), (' Bitter ', 1)]

3. Merge elements in Maplist, the first index value of the tuple is the same, then its second index value is added.

Note: Prepare to use defaultdict. The data obtained are as follows: {' Betty ': 1, ' bought ': 1, ' A ': 1, ' bit ': 1, ' of ': 1, ' Butter ': 2, ' but ': 1, ' the ': 1, ' is ': 1, ' Bitter ': 1}

4. Sort the alphabetical order by key and get the following: [(' A ', ' 1 '), (' Betty ', 1), (' bit ', 1), (' Bitter ', 1), (' bought ', 1), (' but ', 1), (' Butter ', 2), (' O F ', 1), (' The ', 1), (' was ', 1)]

5. Two orders, sorted by value, are as follows: [(' Butter ', 2), (' A ', 1), (' Betty ', 1), (' bit ', 1), (' Bitter ', 1), (' bought ', 1), (' but ', 1), (' of ', 1), (' The ', ' 1 '), (' was ', 1)]

6. Use the slices to remove the higher frequency * Group data

Summary: It is also correct to sort the results on Python3 without defaultdict, Python2 is incorrect. The defaultdict itself is not sequential and must be sorted to differentiate the list.

You can also try to write yourself without using third-party modules

Solution 1 (using defaultdict):

1From collectionsImportDefaultdict2""" Count words. """3 4 defCount_words (S, N):5""Return the n most frequently occuring words in S."""6split_s = S.Split()7Map_list = [(k,1) for K in split_s]8output = defaultdict (int)9For D in Map_list:TenOutput[d[0]] + = d[1] OneOUTPUT1 = dict (Output) ATop_n = sorted (Output1.items (), Key=lambda pair:pair[0], Reverse=false) -Top_n = sorted (Top_n, Key=lambda pair:pair[1], reverse=true) -  the     returnTOP_N[:N] -  -  - defTest_run (): +""" Test count_words () with some inputs. """ -     Print(Count_words ("Cat Bat Mat cat bat Cat", 3)) +     Print(Count_words ("Betty bought a bit of butter but the butter was bitter", 4)) A  at  - if__name__ = = '__main__‘: -Test_run ()
View Code

Solution 2 (using counter)

1From collectionsImportCounter2""" Count words. """3 4 defCount_words (S, N):5""Return the n most frequently occuring words in S."""6split_s = S.Split()7split_s = Counter (nameFornameIn split_s)8     Print(split_s)9Top_n = sorted (Split_s.items (), Key=lambda pair:pair[0], Reverse=false)Ten     Print(Top_n) OneTop_n = sorted (Top_n, Key=lambda pair:pair[1], reverse=true) A     Print(Top_n) -  -     returnTOP_N[:N] the  -  - defTest_run (): -""" Test count_words () with some inputs. """ +     Print(Count_words ("Cat Bat Mat cat bat Cat", 3)) -     Print(Count_words ("Betty bought a bit of butter but the butter was bitter", 4)) +  A  at if__name__ = = '__main__‘: -Test_run () - 
View Code

Python advanced to count the words in Python

Related Article

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.