[python] Sentiment Analysis

Viewer

copydownloadembedprintName: Sentiment Analysis
  1. from textblob import TextBlob
  2. import matplotlib.pyplot as plt
  3. from pyspark import SparkConf, SparkContext
  4. import re
  5. import string
  6. ##OTHER FUNCTIONS/CLASSES
  7. def resolve_emoticon(line):
  8.     emoticon = {
  9.         ':-)' : 'smile',
  10.         ':)' : 'sad',
  11.         ':))' : 'very happy',
  12.         ':)' : 'happy',
  13.         ':((' : 'very sad',
  14.         ':(' : 'sad',
  15.         ':-P' : 'tongue',
  16.         ':-o' : 'gasp',
  17.         '>:-)':'angry'
  18.     }
  19.     for key in emoticon:
  20.         line = line.replace(key, emoticon[key])
  21.         return line
  22.  
  23.  
  24. def abb_bm(line):
  25.     abbreviation_bm = {
  26.     'sy''saya',
  27.     'sk''suka',
  28.     'byk''banyak',
  29.     'sgt' : 'sangat',
  30.     'mcm' : 'macam',
  31.     'bodo':'bodoh',
  32.     'kat':'dekat'
  33.     }
  34.     abbrev = ' '.join (abbreviation_bm.get(word, word) for word in line.split())
  35.     return (resolve_emoticon(abbrev))
  36.  
  37.  
  38. def abb_en(line):
  39.     abbreviation_en = {
  40.     'u''you',
  41.     'thr''there',
  42.     'asap''as soon as possible',
  43.     'lv' : 'love',
  44.     'c' : 'see'
  45.     }
  46.     abbrev = ' '.join (abbreviation_en.get(word, word) for word in line.split())
  47.     return (resolve_emoticon(abbrev))
  48.  
  49. def make_plot(pos,neg):
  50.     #This function plots the counts of positive and negative words
  51.     Polarity = [1,2]
  52.     LABELS = ["Positive", "Negative"]
  53.     Count_polarity = [int(pos), int(neg)]
  54.     plt.xlabel('Polarity')
  55.     plt.ylabel('Count')
  56.     plt.title('Sentiment Analysis - Lexical Based')
  57.     plt.grid(True)
  58.     plt.bar(Polarity, Count_polarity, align='center')
  59.     plt.xticks(Polarity, LABELS)
  60.     plt.show()
  61.  
  62. def remove_features(data_str):
  63.     url_re = re.compile(r'https?://(\S+)')
  64.     num_re = re.compile(r'(\d+)')
  65.     mention_re = re.compile(r'(@|#)(\w+)')
  66.     RT_re = re.compile(r'RT(\s+)')
  67.     data_str = str(data_str)
  68.     data_str = RT_re.sub('', data_str) # remove RT
  69.     data_str = url_re.sub('', data_str) # remove hyperlinks
  70.     data_str = mention_re.sub('', data_str) # remove @mentions and hash
  71.     data_str = num_re.sub('', data_str) # remove numerical digit
  72.     data_str = resolve_emoticon(data_str) # replace emoji
  73.     return data_str.lower()
  74.  
  75. def main(sc,filename):
  76.     # CODE IT YOURSELF  
  77.     rdd = sc.textFile(filename).map(lambda text: remove_features(text)) #remove and replace
  78.     rdd_en = rdd.filter(lambda text: TextBlob(text).detect_language() == 'en').map(lambda text: abb_en(text)) #filter to english
  79.     rdd_ms = rdd.filter(lambda text: TextBlob(text).detect_language() == 'ms').map(lambda text: abb_bm(text)).map(lambda text: str(TextBlob(text).translate(to='en'))) #filter to bahasa and translate to en
  80.     
  81.     rdd = rdd_en.union(rdd_ms)
  82.  
  83.     positive_rdd = rdd.filter(lambda text: TextBlob(text).sentiment.polarity > 0)
  84.     negative_rdd = rdd.filter(lambda text: TextBlob(text).sentiment.polarity < 0)
  85.  
  86.     make_plot(int(positive_rdd.count()),int(negative_rdd.count())) #the cast is just to ensure the value is in integer data type
  87.  
  88. if __name__ == "__main__":
  89.     # Configure your Spark environment
  90.     conf = SparkConf().setMaster("local[*]").setAppName("My Spark Application - Sentiment Analysis")
  91.     sc = SparkContext(conf=conf)
  92.     # CODE IT YOURSELF
  93.     filename = "simple_sentences.txt"
  94.     main(sc, filename)
  95.     sc.stop()

Editor

You can edit this paste and save as new:


File Description
  • Sentiment Analysis
  • Paste Code
  • 06 May-2021
  • 3.19 Kb
You can Share it: