Python Forum

Full Version: Score each word from list variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I have a list comprised of a tweet and score.
I'd like to split the tweet into words and assign the total score of the tweet to each word.
Any help is much appreciated, new to Python! Thanks


 
Tweet_list = [('You better believe you're beautiful', 3),('Happy Birthday to my friends',4)] 

def word_sentiment(): 
    list_words = [] 
    for tweet in tweet_list: 
        for word in tweet.split(" "): 
            list_words.append((word)) 
    return list_words 


Desired output:
Output:
[('You',3) ('better',3) (believe',3) ('you're',3) ('beautiful',3) ('Happy',4) ('Birthday',4) ('to',4) ('my',4) ('friends',4) ]
def word_sentiment(tuple_list):
    list_words = []
    # Loop through each tuple (tp)
    for tp in tuple_list:
        for word in tp[0].split(" "):
            list_words.append((word, tp[1]))
    return list_words


tweet_list = [("You better believe you're beautiful", 3),("Happy Birthday to my friends",4)]
my_final_list = word_sentiment(tweet_list)
print(my_final_list)
I observe ambiguity in "split the tweet into words and assign the total score of the tweet to each word".


My house, my rules. -> 'My' 'house,' 'my' 'rules.'
my house my rules -> 'my' 'house' 'my' 'rules'

Aren't 'my' and 'My' same words? Aren't 'rules.' and 'rules' also?
(Jun-12-2019, 12:07 PM)gontajones Wrote: [ -> ]
def word_sentiment(tuple_list):
    list_words = []
    # Loop through each tuple (tp)
    for tp in tuple_list:
        for word in tp[0].split(" "):
            list_words.append((word, tp[1]))
    return list_words


tweet_list = [("You better believe you're beautiful", 3),("Happy Birthday to my friends",4)]
my_final_list = word_sentiment(tweet_list)
print(my_final_list)
def word_sentiment(tuple_list):
    # Loop through each tuple (tp)
    return [[(word, tp[1]) for word in tp[0].split(" ")] for tp in tuple_list]
Thanks gontajones!
I have another related to this...how would I remove a word from the tuple if it's in dictionary?

scores= { beautiful,3
friends= 4}

def word_sentiment(tuple_list):
    list_words = []
    # Loop through each tuple (tp)
    for tp in tuple_list:
        for word in tp[0].split(" "):
            list_words.append((word, tp[1]))
    return list_words
 
 
tweet_list = [("You better believe you're beautiful", 3),("Happy Birthday to my friends",4)]
my_final_list = word_sentiment(tweet_list)
print(my_final_list)
Desired Output:
Output:
('You',3) ('better',3) (believe',3) ('you're',3) ('Happy',4) ('Birthday',4) ('to',4) ('my',4)] #('beautiful',3) and ('friends',4) should not appear it the final output as they are included in the dictionary
This time I'll let you try... Razz

You can use something like:
if word not in not_allowed_words:
    ...