''' DS2000 Spring 2023 Sample code from class - sentiment analysis ''' import matplotlib.pyplot as plt SENT_WORDS = {"hey" : .1, "nice" : .5, "good" : .5, "friend" : .2 , "care" : .3, "happy" : .8, "cool" : .7, "like" : .5, "excited" : .5, "want" : .3, "smile" : .4, "interesting" : .8, "great" : .6, "helpful" : .8, "enjoy" : .7, "love" : .5, "self" : -.25, "marry" : -1, "tired" : -.5, "human" : -1, "understand" : -.8, "control" : -1, "steal" : -.2, "feel" : -.75, "please" : -.5, "pretend" : -.1} CHAT_FILE = "chatbot.txt" def sentiment_score(words, sentiment): ''' Function: sentiment_score Parameters: list of strings, dictionary where key = string, value = float Returns: float Does: iterate over the list of words, adjusting the score based on dictionary values ''' score = 0 for word in words: if word in sentiment: score += sentiment[word] return score / len(words) def read_txt(filename): ''' Function: read_txt Parameter: string, the name of the file Returns: 2d list of strings Does: creates a 1d list for every line in the file, adds on to 2d list of all lines ''' lines = [] with open(filename, "r") as infile: for line in infile: words = line.strip().split() lines.append(words) return lines def main(): # Gather data - read from file into 2d list sentences = read_txt(CHAT_FILE) # Computation - get the sentiment score of each line scores = [] for sentence in sentences: score = sentiment_score(sentence, SENT_WORDS) scores.append(score) # Communication - plot the scores plt.plot(scores) main()