![]() |
Attach sentiment to each word in a list of tuples - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Attach sentiment to each word in a list of tuples (/thread-2919.html) |
Attach sentiment to each word in a list of tuples - Casper - Apr-19-2017 Hello. The input to the below two functions are a list of string sentences delimited by a comma from a csv file. Each list represents negative and positive tweets. When i append the 'negative' and 'positive' string sentiments they are being added to the end of each sentence, however I need to have the sentiment added to the end of each word. The structure I'm aiming for is to have a list of binomial tuples where each tuple consists of a word and the sentiment. Like this [ ('word', 'positive'), ('word2', 'positive'), ('word3, 'positive') ] ... pos_sentences2 = clean1(pos_sentences) neg_sentences2 = clean1(neg_sentences) def append_pos(): temp = [] for row in pos_sentences2: temp.append((row, 'positive')) return temp def append_neg(): temp = [] for row in neg_sentences2: temp.append((row, 'negative')) return temp pos = append_pos() neg = append_neg() print(pos)This is my current output but I would like the sentiment to be attached to each word rather than each sentence. Thanks.
RE: Attach sentiment to each word in a list of tuples - zivoni - Apr-19-2017 You need to split each sentence into words and then append pairs (word, sentiment) to your list. It can be done by adding another for loop into your original for loop, for row in pos_sentences2: for word in row.split(): temp.append((word, 'positive'))but perhaps its easier do it with a list comprehension. And you dont need to implement basically same function for positive and negative sentiment, instead that you can use sentences and sentiment as parameters for your function. def append_sentiment(sentences, sentiment): return [(word, sentiment) for sentence in sentences for word in sentence.split()]
RE: Attach sentiment to each word in a list of tuples - Casper - Apr-20-2017 It always makes perfect sense once you see the working code. Thanks again your always a great help. RE: Attach sentiment to each word in a list of tuples - ojirgl - Oct-13-2018 (Apr-19-2017, 06:58 PM)zivoni Wrote: You need to split each sentence into words and then append pairs (word, sentiment) to your list. It can be done by adding another for loop into your original for loop, Hi, please, what should I do to achieve the same if I have it in pandas dataframe and have positive or negative numbers to mark the score? Example: id | text | score 12 | I like this | 2 Wanted result: id | text | score 12 | ('I', 2), ('like', 2), ('this', 2) | 2 |