Extract Top N Unique Words from Text

  • Share this:

Code introduction


This function extracts the top N most common unique words from a given text.


Technology Stack : collections.Counter, itertools.islice

Code Type : String processing

Code Difficulty : Intermediate


                
                    
def extract_unique_words(text, num_words=5):
    from collections import Counter
    from itertools import islice

    words = text.split()
    word_counts = Counter(words)
    most_common_words = islice(word_counts.most_common(), num_words)
    unique_words = [word for word, count in most_common_words]
    return unique_words