这是一个利用 Python 和 Flask 框架制作的 Web 应用步伐。它有一个注册系统和一个仪表板。用户可以输入关键字以根据关键字检索及时 Twitter 文本,并对其进行分析以了解客户的感受和情绪。此数据可以在图表中可视化。特别是,该项目利用流行的“Tweepy”API 发掘数据。Tweepy API 及时毗连到 Twitter,并从 Twitter 平台网络元数据和文本。
目的:
- 帮助公司研究客户对特定产物的情绪。
- 帮助系统用户快速高效地分析海量数据。
- 以 -1 到 1 的等级分隔客户情绪,其中 -1 表现对关键字的猛烈负面情绪,1 表现猛烈积极的反应。
- 清晰有效地将网络的数据可视化。
详细的项目实施视频:
视频播放器 00:00 09:11 项目中利用的工具和技术:
硬件:
- 4GB 内存
- Windows 10 操纵系统
- 用于部署的 Google Chrome Web 浏览器
- 用于毗连到 Twitter 的 Internet 毗连
此项目设计是基于软件的,因此硬件设计要求包括一台功能齐备的 64 位 PC,至少具有 4 GB 的 RAM。
软件:
- Python- Python 是一种表明型、高级和通用编程语言。Python 提高了代码的可管理性和可读性,使其成为利用机器学习的顶级应用步伐之一。
- Flask Web 框架(与 python 一起利用)- Flask 是一个 Web 框架。这意味着 flask 为我们提供了工具、库和技术,使我可以或许构建 Web 应用步伐和网页。Flask 是一个后端微框架,它使数据处置惩罚变得简朴明白。
- Tweepy(Twitter API for Python)- Tweepy 是一个开源 Python 包,它为您提供了一种非常方便的方式来利用 Python 访问 Twitter API。Tweepy 包罗一组代表 Twitter 模型和 API 端点的类和方法,它透明地处置惩罚各种实现细节,例如数据编码息争码。
- 实用于 Windows 的 Xampp 服务器上的 Apache SQL - SQL 服务器在本田主机内的 phpMyAdmin 上运行。此数据库用于存储、验证和检索用户的登录凭证。
- 引导 - UI 在 Bootstrap 的帮助下得到增强,这有助于构建现代、直观且响应迅速的网页。
- JQuery- JQuery 用于从 Tweepy API 来回发送和检索数据,并在网页上显示结果。
- HTML/CSS- HTML 和 CSS 是网站前端设计的底子。
构建项目所需的技能:
- 机器学习 - 中等
- 编程技能
- Python- 高级。
- HTML/CSS/JQUERY/BOOTSTRAP- 从底子到中等。
- SQL/DBMS - 底子到中等
- 调试/部署 – 中等
- 可以或许利用 API。
实施项目:
请按照以下步调实施项目:
步调1: 在您的系统上下载并安装 Xampp Server。
步调2: 启动 Apache Xampp 和 MySQL。在 MySQL 中创建一个包罗 3 列(用户名、电子邮件 ID 和密码)的数据库。
步调3:下载并安装 PyCharm。单击 Create-> New Project。为您的项目命名。
步调4:在 Pycharm 中键入以下代码。有关详细的项目文件和层次布局,请参阅此
main.py 文件:
在此文件中,我们首先初始化我们的项目。我们利用 'conn' 对象建立与 SQL 数据库的毗连。
我们设置了一个用户 cookie 变量,该变量在将用户重定向到主页之前查抄用户是否已登录。此脚本还处置惩罚登录/注册页面上的用户输入。
from flask import Flask, render_template, request, redirect, session import mysql.connector from sentiments import second import os app = Flask(__name__) # initializing the user cookie app.secret_key = os.urandom(24) # blueprint to call the second python file in the project. app.register_blueprint(second) # establishing a connection with mysql database made in xampp try: conn = mysql.connector.connect( host="localhost", user="root", password="", database="users") cursor = conn.cursor() except: print("An exception occurred") # call the login template when the url is http://localhost:5000/ @app.route('/') def login(): return render_template('login.html') # call the register template when the url is http://localhost:5000/register @app.route('/register') def register(): return render_template('register.html') @app.route('/home') def home(): if 'user_id' in session: return render_template('home.html') else: return redirect('/') @app.route('/login_validation', methods=['POST']) def login_validation(): email = request.form.get('email') password = request.form.get('password') cursor.execute( """SELECT * from `users` WHERE `email` LIKE '{}' AND `password` LIKE '{}'""".format(email, password)) users = cursor.fetchall() # check if a user has already logged in if len(users) > 0: session['user_id'] = users[0][0] return redirect('/home') else: return redirect('/login') @app.route('/add_user', methods=['POST']) def add_user(): # get user login data and pass the data to database name = request.form.get('uname') email = request.form.get('uemail') password = request.form.get('upassword') cursor.execute("""INSERT INTO `users` (`name`,`email`,`password`) VALUES ('{}','{}','{}')""".format( name, email, password)) conn.commit() cursor.execute( """SELECT * from `users` WHERE `email` LIKE '{}'""".format(email)) myuser = cursor.fetchall() session['user_id'] = myuser[0][0] return redirect('/home') @app.route('/logout') def logout(): # close the session session.pop('user_id') return redirect('/') if __name__ == "__main__": app.run(debug=True) | sentiments.py
这是我们项目中的第二个 python 文件,它在我们的“main.py”文件中注册为蓝图。
此代码从 HTML 页面获取用户输入,该页面指定要搜刮的关键字以及要查看的推文数量。然后,它毗连到 Tweepy API,后者检索推文文本。这段笔墨经过清算,然后分类为不同的情绪(-1 是愤怒/悲伤的情绪,1 是快乐的情绪)。
基于此,将创建饼图并将其保存为图像。此图像稍后在其他 HTML 页面中调用。
from flask import Blueprint, render_template, request import matplotlib.pyplot as plt import os import tweepy import csv import re from textblob import TextBlob import matplotlib matplotlib.use('agg') # register this file as a blueprint second = Blueprint("second", __name__, static_folder="static", template_folder="template") # render page when url is called @second.route("/sentiment_analyzer") def sentiment_analyzer(): return render_template("sentiment_analyzer.html") # class with main logic class SentimentAnalysis: def __init__(self): self.tweets = [] self.tweetText = [] # This function first connects to the Tweepy API using API keys def DownloadData(self, keyword, tweets): # authenticating consumerKey = '//get from Tweepy' consumerSecret = '//get from Tweepy' accessToken = '//insert your access token here' accessTokenSecret = '//Tweepy AccessToken secret here' auth = tweepy.OAuthHandler(consumerKey, consumerSecret) auth.set_access_token(accessToken, accessTokenSecret) api = tweepy.API(auth, wait_on_rate_limit=True) # input for term to be searched and how many tweets to search # searchTerm = input("Enter Keyword/Tag to search about: ") # NoOfTerms = int(input("Enter how many tweets to search: ")) tweets = int(tweets) # searching for tweets self.tweets = tweepy.Cursor( api.search, q=keyword, lang="en").items(tweets) # Open/create a file to append data to csvFile = open('result.csv', 'a') # Use csv writer csvWriter = csv.writer(csvFile) # creating some variables to store info polarity = 0 positive = 0 wpositive = 0 spositive = 0 negative = 0 wnegative = 0 snegative = 0 neutral = 0 # iterating through tweets fetched for tweet in self.tweets: # Append to temp so that we can store in csv later. I use encode UTF-8 self.tweetText.append(self.cleanTweet(tweet.text).encode('utf-8')) # print (tweet.text.translate(non_bmp_map)) #print tweet's text analysis = TextBlob(tweet.text) # print(analysis.sentiment) # print tweet's polarity # adding up polarities to find the average later polarity += analysis.sentiment.polarity # adding reaction of how people are reacting to find average later if (analysis.sentiment.polarity == 0): neutral += 1 elif (analysis.sentiment.polarity > 0 and analysis.sentiment.polarity <= 0.3): wpositive += 1 elif (analysis.sentiment.polarity > 0.3 and analysis.sentiment.polarity <= 0.6): positive += 1 elif (analysis.sentiment.polarity > 0.6 and analysis.sentiment.polarity <= 1): spositive += 1 elif (analysis.sentiment.polarity > -0.3 and analysis.sentiment.polarity <= 0): wnegative += 1 elif (analysis.sentiment.polarity > -0.6 and analysis.sentiment.polarity <= -0.3): negative += 1 elif (analysis.sentiment.polarity > -1 and analysis.sentiment.polarity <= -0.6): snegative += 1 # Write to csv and close csv file csvWriter.writerow(self.tweetText) csvFile.close() # finding average of how people are reacting positive = self.percentage(positive, tweets) wpositive = self.percentage(wpositive, tweets) spositive = self.percentage(spositive, tweets) negative = self.percentage(negative, tweets) wnegative = self.percentage(wnegative, tweets) snegative = self.percentage(snegative, tweets) neutral = self.percentage(neutral, tweets) # finding average reaction polarity = polarity / tweets # printing out data # print("How people are reacting on " + keyword + " by analyzing " + str(tweets) + " tweets.") # print() # print("General Report: ") if (polarity == 0): htmlpolarity = "Neutral" # print("Neutral") elif (polarity > 0 and polarity <= 0.3): htmlpolarity = "Weakly Positive" # print("Weakly Positive") elif (polarity > 0.3 and polarity <= 0.6): htmlpolarity = " ositive" elif (polarity > 0.6 and polarity <= 1): htmlpolarity = "Strongly Positive" elif (polarity > -0.3 and polarity <= 0): htmlpolarity = "Weakly Negative" elif (polarity > -0.6 and polarity <= -0.3): htmlpolarity = "Negative" elif (polarity > -1 and polarity <= -0.6): htmlpolarity = "strongly Negative" self.plotPieChart(positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword, tweets) print(polarity, htmlpolarity) return polarity, htmlpolarity, positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword, tweets def cleanTweet(self, tweet): # Remove Links, Special Characters etc from tweet return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t]) | (\w +:\ / \ / \S +)", " ", tweet).split()) # function to calculate percentage def percentage(self, part, whole): temp = 100 * float(part) / float(whole) return format(temp, '.2f') # function which sets and plots the pie chart. The chart is saved in an img file every time the project is run. # The previous image is overwritten. This image is called in the html page. def plotPieChart(self, positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword, tweets): fig = plt.figure() labels = ['Positive [' + str(positive) + '%]', 'Weakly Positive [' + str(wpositive) + '%]', 'Strongly Positive [' + str(spositive) + '%]', 'Neutral [' + str(neutral) + '%]', 'Negative [' + str(negative) + '%]', 'Weakly Negative [' + str(wnegative) + '%]', 'Strongly Negative [' + str(snegative) + '%]'] sizes = [positive, wpositive, spositive, neutral, negative, wnegative, snegative] colors = ['yellowgreen', 'lightgreen', 'darkgreen', 'gold', 'red', 'lightsalmon', 'darkred'] patches, texts = plt.pie(sizes, colors=colors, startangle=90) plt.legend(patches, labels, loc="best") plt.axis('equal') plt.tight_layout() strFile = r"C:\Users\LENOVO\PycharmProjects\SentimentAnalysis\static\images\plot1.png" if os.path.isfile(strFile): os.remove(strFile) # Opt.: os.system("rm "+strFile) plt.savefig(strFile) plt.show() @second.route('/sentiment_logic', methods=['POST', 'GET']) def sentiment_logic(): # get user input of keyword to search and number of tweets from html form. keyword = request.form.get('keyword') tweets = request.form.get('tweets') sa = SentimentAnalysis() # set variables which can be used in the jinja supported html page polarity, htmlpolarity, positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword1, tweet1 = sa.DownloadData( keyword, tweets) return render_template('sentiment_analyzer.html', polarity=polarity, htmlpolarity=htmlpolarity, positive=positive, wpositive=wpositive, spositive=spositive, negative=negative, wnegative=wnegative, snegative=snegative, neutral=neutral, keyword=keyword1, tweets=tweet1) @second.route('/visualize') def visualize(): return render_template('PieChart.html') | SentimentAnalyzer.py 模板。(为步伐的主逻辑呈现结果的模板)
此模板要求用户输入他们感爱好的主题/单词,以及用户想要分析的基于该主题的推文数量。
请注意,Twitter 有逐日和每小时的速率限定,不能超过。
此表单将数据通报到 second.py 文件,该文件计算输出并设置 “jinja” 变量。(Jinja 答应在 python 和 HTML 之间通报值)。
然后,这些变量会向用户显示输出。
详细项目实施指南:
- 用户通过单击“创建帐户”注册页面验证来创建一个包罗全部必须验证的新帐户。通过利用 cookie 来防止 URL 重写。
- 乐成注册/登录后,用户将被定向到主页。
- Home Page 有一个 bootstrap 轮播 Slider。在左上角,将检索 Cookie 并显示已登任命户的名称。此 cookie 还可以防止网站挟制(假如用户没有正确登录,则无法直接访问 /home URL)。
- 主页利用 cookie 利用注册名称欢迎用户,
- 用户可以利用顶部的导航栏进行导航。单击“开始”以转到主模块屏幕。
- 用户输入关键字和要分析的推文数量。这两个字段都需要填写。用户单击 analyze。系统毗连到 Tweepy,获取最新的推文,对其进行分析,并在相应的字段中显示结果。
- 用户可以单击报告底部的 generate Visualization 按钮。这将根据报表生成饼图。
- 当用户点击“how this project works”时,他们会被重定向到 tweepy 文档。
- 用户可以点击 “logout” 注销并竣事他们的会话。
用例图
实际项目中的应用:
Twitter 拥有 3.3 亿月活跃用户,这使企业可以或许在没有中介的情况下接触到广泛的受众并与客户建立联系。倒霉的一面是,信息太多,品牌很难快速发现大概损害其业务的负面交际提及。
这就是为什么情绪分析(涉及监控交际媒体平台上对话中的情绪)已成为交际媒体营销的关键计谋。倾听客户在 Twitter 上的感受可以让公司了解他们的受众,了解关于他们的品牌和竞争对手的评价,并发现行业的新趋势。公司可以迅速采取行动。这个想法甚至可以扩展到普通用户,其中本地关键字和主题标签可用于分析 Twitter 文本中的情绪。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |