Polyglot-Based Word Frequency Calculator

  • Share this:

Code introduction


This function uses the Polyglot library to calculate the frequency of each word in the given text. It first creates a Polyglot Text object, then retrieves the words and their frequencies from the text, and converts the result into a JSON string.


Technology Stack : Polyglot

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_word_frequency(text, language='en'):
    """
    This function uses the Polyglot library to calculate the frequency of each word in the given text.
    """
    from polyglot.text import Text
    import json

    # Create a Polyglot Text object
    polyglot_text = Text(text, hint_language_code=language)

    # Get the words and their frequencies
    word_freq = polyglot_text.words.get_frequencies()

    # Convert the word frequencies to a JSON string
    word_freq_json = json.dumps(word_freq)

    return word_freq_json                
              
Tags: