Repository navigation
Expand file tree
/
Copy pathspark-emotion-analysis.py
More file actions
45 lines (39 loc) · 1.63 KB
/
Copy pathspark-emotion-analysis.py
File metadata and controls
45 lines (39 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from pyspark.sql import SparkSession
from pyspark import SQLContext,SparkConf
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from textblob import TextBlob
# conf = SparkConf().setAppName("ReadCSV")
# sqlContext = SQLContext(conf=conf)
# sparkSession = SparkSession.builder.appName("spark-readfile").getOrCreate()
# df_load = sparkSession.read.csv('hdfs:///project/samples.csv')
# df_load.show()
def get_score(sentence):
blob = TextBlob(sentence)
return blob.sentences[0].sentiment.polarity
def run_spark():
spark = SparkSession.builder.master("local").appName("Word Count").getOrCreate()
df = spark.read.format("csv").option("header", "true").load("hdfs:///project/samples
sqlContext=SQLContext(spark)
sqlContext.registerDataFrameAsTable(df, "table1")
sentences=sqlContext.sql("""SELECT `reviews.rating`,`reviews.text` FROM table1""").rdd
sentences.collect()
alist=sentences.map(lambda x:x[0] if x[0] is not None else 0).collect()
blist=sentences.map(lambda x:get_score(x[1]) if x[1] is not None else 0).collect()
return alist,blist
def draw_plots(alist,blist)
alist,blist = run_spark()
t_plt, = plt.plot(np.arange(1, len(alist)+1), alist, 'r')
v_plt, = plt.plot(np.arange(1, len(alist)+1), blist)
plt.title('NLP Emotion Analysis') #
plt.xlabel('epoch') #
plt.ylabel('score') #
plt.legend((t_plt, v_plt), ('rating', 'score')) #
plt.savefig("result.png")
with open("x1.txt","w+") as input_:
input_.write(','.join([str(x) for x in alist]))
input_.write(','.join([str(x) for x in blist]))
if __name__=='__main__':
run_spark()