Random Word Frequency Counter with User Input

  • Share this:

Code introduction


This function uses the `questionary` library to prompt the user for text input and then returns a dictionary containing the top `num_words` most frequently occurring words in the text.


Technology Stack : Questionary, collections.Counter, re

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_word_count(text, num_words=5):
    """
    This function uses the `questionary` library to prompt the user for a text input and then
    returns a dictionary with the top `num_words` most frequently occurring words in the text.
    """
    from questionary import Text
    from collections import Counter
    import re

    # Prompt the user for text input
    text_input = Text("Please enter a text: ").ask()

    # Tokenize the text into words and count their occurrences
    words = re.findall(r'\w+', text_input.lower())
    word_counts = Counter(words)

    # Get the top `num_words` most common words
    top_words = word_counts.most_common(num_words)

    # Return a dictionary of the top words
    return dict(top_words)