📜  使用Python进行文本检测

📅  最后修改于: 2022-05-13 01:55:36.494000             🧑  作者: Mango

使用Python进行文本检测

Python语言被广泛用于现代机器学习和数据分析。可以通过Python检测图像、语音,甚至可以检测对象。目前,我们将通过将文本分类为正面、负面或中性来检测来自用户的文本是给人一种正面的感觉还是负面的感觉。在代码中,使用了Vader 情感分析Tkinter 。 Tkinter 是用于创建 GUI 应用程序的标准 GUI 库。

Anaconda 中所需的安装:

  • tkinter:此模块用于创建简单的 GUI 应用程序。该模块通常与Python一起预装,但要在外部安装它,请在终端中键入以下命令。
    使用 conda 命令。
conda install -c anaconda tk

Linux 用户也可以使用以下命令。

sudo apt-get install python3-tk
  • nltk:该模块用于使计算机理解自然语言。要安装它,请在终端中键入以下命令。
    使用康达。
conda install -c anaconda nltk

使用点子。

pip install nltk
  • numpy:这个模块是使用Python进行科学计算的基础包。要安装它,请在终端中键入以下命令。
    使用康达。
conda install -c conda-forge numpy

使用点子。

pip install numpy
  • pandas:该模块用于数据分析。它提供高度优化的性能,后端源代码完全用 C 或Python编写。要安装它,请在终端中键入以下命令。
    使用康达
conda install -c anaconda pandas

使用点子。

pip install pandas
  • matplotlib:这个模块是Python中用于二维数组图的惊人可视化库。 Matplotlib 是一个基于 NumPy 数组构建的多平台数据可视化库。要安装它,请在终端中键入以下命令。
    使用康达。
conda install -c conda-forge matplotlib

使用点子。

pip install matplotlib

VADER 情绪分析

VADER(Valence Aware Dictionary and sEntiment Reasoner)是一种基于词典和规则的情感分析工具,专门针对社交媒体中表达的情感。 VADER 使用组合 情感词典是词汇特征(例如单词)的列表,通常根据其语义方向将其标记为正面或负面。 VADER 不仅告诉我们积极性和消极性得分,还告诉我们情绪的积极或消极程度。

注意:更多信息请参考Python |使用 VADER 进行情绪分析。

下面是实现。

Python3
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tkinter import *
import tkinter.messagebox
from nltk.sentiment.vader import SentimentIntensityAnalyzer
  
     
class analysis_text():
     
    # Main function in program
    def center(self, toplevel):
         
        toplevel.update_idletasks()
        w = toplevel.winfo_screenwidth()
        h = toplevel.winfo_screenheight()
        size = tuple(int(_) for _ in
                     toplevel.geometry().split('+')[0].split('x'))
         
        x = w/2 - size[0]/2
        y = h/2 - size[1]/2
        toplevel.geometry("%dx%d+%d+%d" % (size + (x, y)))
  
    def callback(self):
        if tkinter.messagebox.askokcancel("Quit",
                                          "Do you want to leave?"):
            self.main.destroy()
  
    def setResult(self, type, res):
         
        #calculated comments in vader analysis
        if (type == "neg"):
            self.negativeLabel.configure(text =
                                         "you typed negative comment : "
                                         + str(res) + " % \n")
        elif (type == "neu"):
            self.neutralLabel.configure( text =
                                        "you typed  comment : "
                                        + str(res) + " % \n")
        elif (type == "pos"):
            self.positiveLabel.configure(text
                                        = "you typed positive comment: "
                                         + str(res) + " % \n")
         
  
    def runAnalysis(self):
         
        sentences = []
        sentences.append(self.line.get())
        sid = SentimentIntensityAnalyzer()
         
        for sentence in sentences:
             
            # print(sentence)
            ss = sid.polarity_scores(sentence)
             
            if ss['compound'] >= 0.05 :
                self.normalLabel.configure(text =
                                           " you typed positive statement: ")
    
            elif ss['compound'] <= - 0.05 :
                self.normalLabel.configure(text =
                                           " you typed negative statement")
    
            else :
             self.normalLabel.configure(text =
                                        " you normal typed  statement: ")
            for k in sorted(ss):
                self.setResult(k, ss[k])
        print()
         
  
    def editedText(self, event):
        self.typedText.configure(text = self.line.get() + event.char)
         
  
    def runByEnter(self, event):
        self.runAnalysis()
  
 
    def __init__(self):
        # Create main window
        self.main = Tk()
        self.main.title("Text Detector system")
        self.main.geometry("600x600")
        self.main.resizable(width=FALSE, height=FALSE)
        self.main.protocol("WM_DELETE_WINDOW", self.callback)
        self.main.focus()
        self.center(self.main)
  
        # addition item on window
        self.label1 = Label(text = "type a text here :")
        self.label1.pack()
  
        # Add a hidden button Enter
        self.line = Entry(self.main, width=70)
        self.line.pack()
  
        self.textLabel = Label(text = "\n",
                               font=("Helvetica", 15))
        self.textLabel.pack()
        self.typedText = Label(text = "",
                               fg = "blue",
                               font=("Helvetica", 20))
        self.typedText.pack()
  
        self.line.bind("",self.editedText)
        self.line.bind("",self.runByEnter)
  
  
        self.result = Label(text = "\n",
                            font=("Helvetica", 15))
        self.result.pack()
        self.negativeLabel = Label(text = "",
                                   fg = "red",
                                   font=("Helvetica", 20))
        self.negativeLabel.pack()
        self.neutralLabel  = Label(text = "",
                                   font=("Helvetica", 20))
        self.neutralLabel.pack()
        self.positiveLabel = Label(text = "",
                                   fg = "green",
                                   font=("Helvetica", 20))
        self.positiveLabel.pack()
        self.normalLabel =Label (text ="",
                                 fg ="red",
                                 font=("Helvetica", 20))
        self.normalLabel.pack()
         
# Driver code
myanalysis = analysis_text()
mainloop()


输出:

文本检测阳性文本检测阴性