Question: In your if __name__ == '__main__' section, write an interface which allows in a user to pass in the name of a file through the
In your if __name__ == '__main__' section, write an interface which allows in a user to pass in the name of a file through the command line like this:
python sentiment.py some_file.txt If the user fails to pass in a file name, your code should handle the situation without throwing an Exception by printing a message to the console instructing the user to input a file name.
Otherwise, your code should load in the text from the file, extract the list of unique words, and compute the sentiment score using the dictionary from sentiment.txt. It should then print out the word Positive to the console if the file score is > 0, Negative if the file score is < 0, and Neutral otherwise. There should be no other output to the console.
Below is my current code please help me write out the above requirements in python 3.8
Please download txt files from the below link for this problem
https://drive.google.com/drive/folders/1DlLGn90KSxBVdcW0ETX1P__B6GWwHBUc?usp=sharing
import string # import for build in list of punctuations def load_score_dict(filename="sentiment.txt"): # function with argument score_dict = dict() # dictionary for word-scores storage with open(filename) as f: # open file for line in f.readlines(): # read lines if len(line.strip()) != 0: # check empty line if line.strip()[0] != "#": # check line start with # word, score = line.strip().split() # split words and score score_dict[word] = score[1:-1] # add to dictionary return score_dict # return result def get_words(my_sentence): # function to take sentence as input for i in string.punctuation: # punctuation list my_sentence = my_sentence.replace(i, "") # replace punctuation with "" my_sentence = my_sentence.lower() # convert to lower case ans = my_sentence.strip().split() # remove whitespaces and split to a list ans = list(set(ans)) # remove duplicates using set return ans def score_sentence(my_sentence, scores): # function to take sentence and score as input for i in string.punctuation: my_sentence = my_sentence.replace(i, "") # replace punctuation with "" words = set(my_sentence.split()) # remove duplicates words = list(words) # return to list form l = scores.keys() # dictionary c = 0 # score for i in words: # loop through words in a list if i in l: # if word has a score if i.isalpha(): # if word is alphanumeric c += scores[i] # add score to c return c
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
