lecture_8_practice

pdf

School

University of California, Davis *

*We aren’t endorsed by this school

Course

1

Subject

Computer Science

Date

Feb 20, 2024

Type

pdf

Pages

3

Uploaded by DukeFly4004

Report
lecture_8_practice January 30, 2024 1 Practice: Sentiment Analysis and Loop Variables Now it’s your turn to practice sentiment analysis and loop variables 1.1 Sentiment Analyasis First run the code to load up the Sentiment Intensity Analyzer [7]: import nltk nltk . download([ "vader_lexicon" ]) from nltk.sentiment import SentimentIntensityAnalyzer sia = SentimentIntensityAnalyzer() [nltk_data] Downloading package vader_lexicon to [nltk_data] /home/jovyan/nltk_data… [nltk_data] Package vader_lexicon is already up-to-date! Also, look at this example from the demo of running sentiment analysis: [8]: sentence = "I love love love pizza!!!!!!!!" sia . polarity_scores(sentence)[ "compound" ] [8]: 0.941 Now, copy that two lines of code above, and try out your own sentences, and run the sentiment analysis on them [9]: sentence = "This is an ok example" sia . polarity_scores(sentence)[ "compound" ] [9]: 0.296 Try several sentences and see how the Sentiment Intensity Analyzer handles them [10]: sentence = "This is a horrible example" sia . polarity_scores(sentence)[ "compound" ] [10]: -0.5423 1
1.2 Loop variables Now let’s practice with loop variables. Below is a for loop which goes through each letter in the word “Mississipi”. [11]: for letter in "Mississipi" : print (letter) M i s s i s s i p i Make another copy of that loop, but add a variable before the loop called num_letters and use it count how many letters were in the word “Mississipi”. At the end display the number of letters. [12]: num_letters = 0 for letter in "Mississipi" : print (letter) num_letters += 1 print ( "There were " + str (num_letters) + " letters" ) M i s s i s s i p i There were 10 letters Make another copy of what you just did, but this time also count the number of “i”s. Make a variable called num_i to count how many “i”s. Hint: To see if a letter is an “i”, check if letter == "i" At the end print out how many of the letters were “i”s and what percentage of the word was “i”s. 2
[13]: num_letters = 0 num_i = 0 for letter in "Mississipi" : print (letter) num_letters += 1 if (letter == "i" ): num_i += 1 print ( "There were " + str (num_letters) + " letters" ) percent_i = num_i / num_letters * 100 print ( "i's made up " + str (percent_i) + " percent of the word" ) M i s s i s s i p i There were 10 letters i's made up 40.0 percent of the word 3
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help