-
Notifications
You must be signed in to change notification settings - Fork 1
/
sentiment_analysis.py
138 lines (111 loc) ยท 6.05 KB
/
sentiment_analysis.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# -*- coding: utf-8 -*-
from pyspark.sql import SparkSession
from pyspark.sql import Row
from pyspark.sql.types import StringType
from pyspark.sql.functions import explode, split, to_date, col, regexp_replace, decode, row_number, encode, udf, when, lit, concat, sum
from pyspark.sql.window import Window
from starbase import Connection
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
# hbase ์ฐ๋
c = Connection()
twitter = c.table("twitter")
if (twitter.exists()):
twitter.drop()
twitter.create("moon", "unification", "dprk")
batch = twitter.batch()
def analysis(folder_name):
tweets = spark.read.load("hdfs:///user/maria_dev/project/data/" + folder_name + "/clean_data.csv",
format="csv", sep=",", inferSchema="true", header="true", encoding="utf-8")
# parse date type
tweets = tweets.withColumn("date", to_date("date"))
# date๋ณ ์ธ๊ธ๋
tweets_num = tweets.groupBy("date").count().orderBy("date", ascending=0)
tweets_num = tweets_num.na.drop()
# flatten word
tweets = tweets.withColumn("word", explode(split("word", '\\|')))
# date๋ณ word count
tweets = tweets.groupBy(["word", "date"]).count().orderBy(["date", "count"], ascending=[0, 0])
# word์ pos ๋๋๊ธฐ
split_col = split(tweets.word, "\\,")
tweets = tweets.withColumn("split_word", split_col.getItem(0))
tweets = tweets.withColumn("pos", split_col.getItem(1))
# ๊ธ์ ๋ถ์ ๊ตฌํ๊ธฐ
udf_calc = udf(get_sentiment, StringType())
tweets = tweets.withColumn("sentiment", udf_calc(col("split_word"), col("pos")))
# ๊ธ๋ถ์ ํผ์ผํธ ๊ณ์ฐ
pos_percentage = tweets.groupBy(["date", "sentiment"]).sum().withColumnRenamed("sum(count)", "count")\
.withColumn("total", sum("count").over(Window.partitionBy("date")))\
.withColumn("percent", (col("count") / col("total")) * 100)\
.filter(col("sentiment").isin(["POS", "NEG"]))\
.select(["date", "sentiment", "percent"])\
.orderBy(["date", "percent"], ascending=[0,0])
# # date๋ณ ๋ง์ word 15๊ฐ ์ถ์ถ
w = Window().partitionBy("date").orderBy(col("count").desc())
tweets = tweets.withColumn("rn", row_number().over(w)).where(col("rn") <= 15)\
.select("split_word", "date", "count", "pos", "sentiment")\
.orderBy(["date", "rn"], ascending=[0,1])
# ์ฉ์ธ์ '-๋ค' ์ถ๊ฐ
tweets = tweets.withColumn("split_word",\
when((tweets.pos == 'PV') | (tweets.pos == 'PA'), concat(col("split_word"), lit("๋ค"))).otherwise(tweets.split_word))
# nlp ์๋ ๊ฒ ์ฒ๋ฆฌ('๊น์ '์)
tweets = tweets.withColumn("split_word",\
when(tweets.split_word == '๊น์ ', concat(col("split_word"), lit("์"))).otherwise(tweets.split_word))
import_data(folder_name, tweets, pos_percentage, tweets_num)
# ๊ฐ์ ์ฌ์
def make_sentiment_dict():
global dict_NNG, dict_VV, dict_NNP, dict_VA
sentiment_df = spark.read.load("hdfs:///user/maria_dev/polarity.csv",
format="csv", sep=",", inferSchema="true", header="true")
sentiment_df = sentiment_df.filter(~sentiment_df.ngram.contains(";"))
filter_NNG = sentiment_df.filter(sentiment_df.ngram.contains("NNG"))
split_NNG = filter_NNG.withColumn("ngram", split(filter_NNG["ngram"], "/").getItem(0))
split_NNG = split_NNG.withColumn("ngram", regexp_replace("ngram", "\*", ""))
dict_NNG = split_NNG.toPandas().set_index("ngram")["max.value"].to_dict()
filter_VV = sentiment_df.filter(sentiment_df.ngram.contains("VV"))
split_VV = filter_VV.withColumn("ngram", split(filter_VV["ngram"], "/").getItem(0))
split_VV = split_VV.withColumn("ngram", regexp_replace("ngram", "\*", ""))
dict_VV = split_VV.toPandas().set_index("ngram")["max.value"].to_dict()
filter_NNP = sentiment_df.filter(sentiment_df.ngram.contains("NNP"))
split_NNP = filter_NNP.withColumn("ngram", split(filter_NNP["ngram"], "/").getItem(0))
split_NNP = split_NNP.withColumn("ngram", regexp_replace("ngram", "\*", ""))
dict_NNP = split_NNP.toPandas().set_index("ngram")["max.value"].to_dict()
filter_VA = sentiment_df.filter(sentiment_df.ngram.contains("VA"))
split_VA = filter_VA.withColumn("ngram", split(filter_VA["ngram"], "/").getItem(0))
split_VA = split_VA.withColumn("ngram", regexp_replace("ngram", "\*", ""))
dict_VA= split_VA.toPandas().set_index("ngram")["max.value"].to_dict()
def get_sentiment(word, pos):
try:
if(pos == "NC"):
return dict_NNG[word.encode("utf-8").decode("utf-8")]
elif(pos == "NQ"):
return dict_NNP[word.encode("utf-8").decode("utf-8")]
elif(pos == "PV"):
return dict_VV[word.encode("utf-8").decode("utf-8")]
elif(pos == "PA"):
return dict_VA[word.encode("utf-8").decode("utf-8")]
else:
return None
except KeyError, e:
return None
def import_data(folder_name, tweets, pos_percentage, tweets_num):
if batch:
index = 1
for row in tweets.rdd.collect():
batch.insert(str(row["date"]), { folder_name : { "word%s" % index : row["split_word"] }})
batch.insert(str(row["date"]), { folder_name : { "sentiment%s" % index : row["sentiment"] }})
batch.insert(str(row["date"]), { folder_name : { "count%s" % index : row["count"] }})
index = index + 1 if (index < 15) and (str(row["date"]) == prev_date) else 1
prev_date = str(row["date"])
for row in pos_percentage.rdd.collect():
batch.insert(str(row["date"]), { folder_name : { row["sentiment"] : row["percent"] }})
for row in tweets_num.rdd.collect():
batch.insert(str(row["date"]), { folder_name : { "all" : row["count"] }})
batch.commit(finalize=True)
if __name__ == '__main__':
spark = SparkSession.builder.appName("sentiment_analysis").getOrCreate()
make_sentiment_dict()
analysis("moon")
# analysis("unification")
# analysis("dprk")