How to code result of word search to count number of occurence of word

Viewed 150

I am trying to count the number of occurrences of words from a list. I need the result to be (word, # of occurrence) however I keep getting (word, 1) (word, 2) (word,3), when it should be giving me (word,3).

All the variables of library, document, and dictionary are defined in another area.

I believe my code is 99% correct but the result is not doing what I need it to.

def (word_search) : 
    results = [] 

    search_word = dictionary [0]

    for search_word in dictionary: 

    count = 0 

    for document in library: 

       for word in document: 

          if search_word == word : 

            count = count + 1

            results.append((word,count)) 

     return (results) 
4 Answers

That's because results is a list of tuples and you keep appending values to it whenever you find a new word occurrence. return (results[-1]) should work, but there is a simpler way to write this function, without the use of a list. I'll let you figure it out since you're still learning :)

maybe you have to ident after the loop:

results = [] 

search_word = dictionary [0]

for search_word in dictionary: 

   count = 0 

   for document in library: 

      for word in document: 

         if search_word == word : 

           count = count + 1

           results.append((word,count)) 

 return (results) 

How about trying out a solution that uses a Python dict (different from your variable dictionary)? In fact, there's a really nifty version of the python dict provided by Python called a defaultdict that can be initialised to a specific value if a key does not exist.

You could code something out like this:

from collections import defaultdict

def (word_search) : 
    results = defaultdict(int) # Make the dict use integers as the default entry value, set it to 0 if key does not exist

    search_word = dictionary [0]

    for search_word in dictionary: 

       for document in library: 

           for word in document: 

               if search_word == word : 

                   results[word] += 1 # Increment the count for the matched word


    return results.items() # Return the counts as a set of tuples

This would produce a set of tuples containing the count of each word!

Note: I fixed the indentation of the for loops too, in case that was causing the issue


Additionally, to improve efficiency, you could produce a count of all words and simply retrieve the counts of your search words at the end, thereby reducing the complexity from O(n^3) to O(n^2):

from collections import defaultdict

def (word_search) : 
    counts = defaultdict(int) # Make the dict use integers as the default entry value, set it to 0 if key does not exist
    for document in library: 

       for word in document: 

           counts[word] += 1 # Increment the count the given word

    # Loop through and extract just the counts of the words you're interested in
    results = []

    for search_word in dictionary: 
        results.append((search_word, counts[search_word]))

    return results

This should reduce your runtime significantly if your documents are very large!

This might help you-

   str='bob sam jeff jeff bob jeff'
    x={}
    for i in str.split():
        if i in x.keys():
            x[i]+=1
        else:
            x[i]=1
    print (x)

Output

{'bob': 2, 'sam': 1, 'jeff': 3}
Related