根据Python中的极性从Textblob中获取正面和负面的词(感伤分析)

时间:2018-04-09 11:05:57

标签: python python-3.x machine-learning sentiment-analysis textblob

我有一个文本blob,如果极性为>我将文本分类为正数。 0,中性if = 0,如果< 0 0。 我怎样才能得到正在分类为积极,消极或中立的词语?

2 个答案:

答案 0 :(得分:1)

我希望以下代码能为您提供帮助:

from textblob import TextBlob
from textblob.sentiments import NaiveBayesAnalyzer
import nltk
nltk.download('movie_reviews')
nltk.download('punkt')

text          = "I feel the product is so good" 

sent          = TextBlob(text)
# The polarity score is a float within the range [-1.0, 1.0]
# where negative value indicates negative text and positive
# value indicates that the given text is positive.
polarity      = sent.sentiment.polarity
# The subjectivity is a float within the range [0.0, 1.0] where
# 0.0 is very objective and 1.0 is very subjective.
subjectivity  = sent.sentiment.subjectivity

sent          = TextBlob(text, analyzer = NaiveBayesAnalyzer())
classification= sent.sentiment.classification
positive      = sent.sentiment.p_pos
negative      = sent.sentiment.p_neg

print(polarity,subjectivity,classification,positive,negative)

答案 1 :(得分:0)

一定要给维德一个机会。 Vader 是一种基于规则的情感分析工具,适用于社交媒体文本和常规文本。

import SwiftUI
import MapKit

struct ContentView: View {
    @State private var centerCoordinates = CLLocationCoordinate2D()
    @State private var showingConfirmation = false
    @State private var showingAlert = false
    var body: some View {
        VStack {
            GeometryReader { geo in
                ZStack {
                    MapView(centerCoordinate: $centerCoordinates)
                        .edgesIgnoringSafeArea(.all)
                        .blur(radius: showingConfirmation ? 6.0 : 0)
                    Circle()
                        .fill(Color.blue)
                        .opacity(0.3)
                        .frame(width: 32, height: 32)
                        .blur(radius: showingConfirmation ? 6.0 : 0)
                    Text("Get Coordinates").bold()
                        .foregroundColor(.primary)
                        .padding()
                        .background(Color.blue)
                        .clipShape(Capsule())
                        .blur(radius: showingConfirmation ? 6.0 : 0)
                        .offset(x: 0, y: geo.size.height * 0.45)
                        .onTapGesture {
                            print(centerCoordinates)
                            showingAlert = true
                        }.disabled(showingConfirmation)

                    if showingConfirmation {
                        Rectangle()
                            .fill(Color.clear)
                            .frame(height: 500)
                            .overlay(
                                
                                VStack {
                                    Text("Latitude and Longitude copied!")
                                        .font(.title)
                                        .bold()
                                        .lineLimit(3)
                                    Button(action: {self.showingConfirmation = false}){
                                        Text("Ok")
                                            .fontWeight(.bold)
                                            .padding()
                                            .foregroundColor(.white)
                                            .background(Color.blue)
                                            .cornerRadius(10)
                                    }

                                }
                            )
                    }
                }
            }
        }
        .actionSheet(isPresented: $showingAlert) {
            ActionSheet(title: Text("Your coordinates are: \nLatitude: \(centerCoordinates.latitude) \nLongitude: \(centerCoordinates.longitude)"), message: nil, buttons: [
                .default(Text("Ok")),
                .default(Text("Copy Latitude and Longitude")) {
                    let myCoordinates = [String(centerCoordinates.latitude), String(centerCoordinates.longitude)]
                    let pasteboard = UIPasteboard.general
                    pasteboard.strings = myCoordinates
                    showingConfirmation = true
                }
            ]
            )
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .preferredColorScheme(.dark)
    }
}

struct MapView: UIViewRepresentable {
    
    @Binding var centerCoordinate: CLLocationCoordinate2D
    
    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        mapView.delegate = context.coordinator
        return mapView
    }
    
    func updateUIView(_ uiView: MKMapView, context: Context) {
        
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, MKMapViewDelegate {
        var parent: MapView
        
        init(_ parent: MapView) {
            self.parent = parent
        }
        
        func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
            parent.centerCoordinate = mapView.centerCoordinate
        }
    }
    
    
    
    
   
}

struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView(centerCoordinate: .constant(MKPointAnnotation.example.coordinate))
    }
}

extension MKPointAnnotation {
    static var example: MKPointAnnotation {
        let annotation = MKPointAnnotation()
        annotation.title = "Current Stay"
        annotation.subtitle = "Temporary Maryland Abode"
        annotation.coordinate = CLLocationCoordinate2D(latitude: 20, longitude: -70)
        
        return annotation
    }
}

输出

# import SentimentIntensityAnalyzer class 
import nltk
from nltk.tokenize import word_tokenize, RegexpTokenizer
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer 
  
# function to print sentiments 
# of the sentence. 
def sentiment_scores(sentence): 
  
    # Create a SentimentIntensityAnalyzer object. 
    sid_obj = SentimentIntensityAnalyzer() 
  
    # polarity_scores method of SentimentIntensityAnalyzer 
    # oject gives a sentiment dictionary. 
    # which contains pos, neg, neu, and compound scores. 
    sentiment_dict = sid_obj.polarity_scores(sentence) 
      
    print("Overall sentiment dictionary is : ", sentiment_dict) 
    print("sentence was rated as ", sentiment_dict['neg']*100, "% Negative") 
    print("sentence was rated as ", sentiment_dict['neu']*100, "% Neutral") 
    print("sentence was rated as ", sentiment_dict['pos']*100, "% Positive") 
  
    print("Sentence Overall Rated As", end = " ") 
  
    # decide sentiment as positive, negative and neutral 
    if sentiment_dict['compound'] >= 0.05 : 
        print("Positive") 
  
    elif sentiment_dict['compound'] <= - 0.05 : 
        print("Negative") 
  
    else : 
        print("Neutral") 
  
  
    
# Driver code 
if __name__ == "__main__" : 
  
    print("\n1st statement :") 
    sentence = "This is the best movie I have watched ever!" 
  
    # function calling 
    sentiment_scores(sentence) 
  
    print("\n2nd Statement :") 
    sentence = "I went to the market"
    sentiment_scores(sentence) 
  
    print("\n3rd Statement :") 
    sentence = "I would not recommend this product to you"
    sentiment_scores(sentence)

参考文献:

  1. https://pypi.org/project/vaderSentiment/
  2. https://www.geeksforgeeks.org/python-sentiment-analysis-using-vader/