Python statistical word count of the idea of a detailed

Source: Internet
Author: User
This article mainly introduces the Python statistical word number of ideas, the text also provides you with no third-party module solutions, interested friends to see together

Problem Description:

Implements the function Count_words () in Python, which enters the string s and the number n and returns the n most frequently occurring words in S. The return value is a tuple list that contains the highest number of n words and their number of occurrences, that is, [(< Word 1>, < times 1>), (< Word 2>, < number 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 is 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):

From collections import Defaultdict "" "Count Words." "" " def count_words (S, N): "" "  Return the n most frequently occuring words in S.  " " split_s = S.split ()  map_list = [(k,1) for K in split_s]  output = defaultdict (int.) for  D in map_list:    OUTPU T[d[0]] + = d[1]  output1 = dict (output)  top_n = sorted (Output1.items (), Key=lambda pair:pair[0], Reverse=false) C8/>top_n = sorted (Top_n, Key=lambda pair:pair[1], reverse=true)  return top_n[:n]def Test_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 is b Itter ", 4)) if __name__ = = ' __main__ ':  test_run ()

Solution 2 (using counter)

From collections import Counter "" "Count Words." "" " def count_words (S, N): "" "  Return the n most frequently occuring words in S.  " " split_s = S.split ()  split_s = Counter (name for name in split_s)  print (split_s)  top_n = sorted (Split_s.items ( ), Key=lambda pair:pair[0], reverse=false)  print (top_n)  top_n = sorted (Top_n, Key=lambda pair:pair[1], reverse =true)  print (top_n)  return top_n[:n]def Test_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 is b Itter ", 4)) if __name__ = = ' __main__ ':  test_run ()

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.