AWS AI Services Programming Series - Part4 (Comprehend)

   Go back to the Task List

  « 5: Syntax Analysis in the Text    7. Clean up »

6: Sentiment Analysis in the Text

In this step, you use Amazon Comprehend APIs to inspect the text and return an inference of the prevailing sentiment (POSITIVE, NEUTRAL, MIXED, or NEGATIVE). Let’s update the code for it.

  1. In AWS Cloud9 console, update dojocomprehend.py file to perform sentiment analysis. Update the code as shown below and save the file.

    Comprehend

    import boto3
    
    client = boto3.client('comprehend')
    
    mytext = "Luxembourg , officially the Grand Duchy of Luxembourg, is a landlocked country in Western Europe. It is bordered by Belgium to the west and north, Germany to the east, and France to the south. Its capital, Luxembourg City, is one of the four official capitals of the European Union (together with Brussels, Frankfurt, and Strasbourg) and the seat of the Court of Justice of the European Union, the highest judicial authority in the EU. Its culture, people, and languages are highly intertwined with its neighbours, making it essentially a mixture of French and German cultures, as evident by the nation's three official languages: French, German, and the national language of Luxembourgish. The repeated invasions by Germany, especially in World War II, resulted in the country's strong will for mediation between France and Germany and, among other things, led to the foundation of the European Union."
    
    response = client.detect_dominant_language(Text= mytext)
    
    thelangcode = response["Languages"][0]["LanguageCode"]
    
    response = client.detect_sentiment(Text=mytext, LanguageCode= thelangcode)
    
    print("Primary sentiment - " + response["Sentiment"])
    print("Neutral sentiment score - " + str(response["SentimentScore"]["Neutral"]))
    print("Mixed sentiment score - " + str(response["SentimentScore"]["Mixed"]))
    print("Positive sentiment score - " + str(response["SentimentScore"]["Positive"]))
    print("Negative sentiment score - " + str(response["SentimentScore"]["Negative"]))	
    

    `

  2. In the code above, you use detect_sentiment method to identify the primary sentiment of the text. You also detect and print the confidence score for other sentiments. Execute python dojocomprehend.py command to run the dojocomprehend.py code.

    Comprehend

  3. Amazon Comprehend can also be used to perform text analysis in a batch process if the text to analysis is large. You can also perform custom classification and custom entity recognition. AWS Dojo plans to create a separate exercise for the customization.

  4. This finishes the workshop. Please follow the next step to clean-up the resources so that you don’t incur any cost.