Advertisement
DragonOsman

Sentiments analyzer.py

Mar 5th, 2017
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. import nltk
  2. import sys
  3. import string
  4.  
  5. from nltk.tokenize import TweetTokenizer
  6.  
  7. class Analyzer():
  8.     """Implements sentiment analysis."""
  9.  
  10.     def __init__(self, positives, negatives):
  11.         """Initialize Analyzer."""
  12.  
  13.         self.positives = []
  14.         self.negatives = []
  15.        
  16.         with open(negatives) as negative:
  17.             for line in negative:
  18.                 if line.startswith(";"):
  19.                     continue
  20.                 else:
  21.                     self.negatives.extend(line.strip())
  22.            
  23.         with open(positives) as positive:
  24.             for line in positive:
  25.                 if line.startswith(";"):
  26.                     continue
  27.                 else:
  28.                     self.positives.extend(line.strip())
  29.  
  30.     def analyze(self, text):
  31.         """Analyze text for sentiment, returning its score."""
  32.  
  33.         tokenizer = nltk.tokenize.TweetTokenizer()
  34.         tokens = tokenizer.tokenize(text)
  35.         score = 0
  36.        
  37.         for token in tokens:
  38.             token.lower()
  39.            
  40.             if token in self.positives:
  41.                 score += 1
  42.             elif token in self.negatives:
  43.                 score -= 1
  44.             else:
  45.                 score = 0
  46.                
  47.         return score
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement