Skip to content

Instantly share code, notes, and snippets.

@fnielsen
Last active May 6, 2021 11:41
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save fnielsen/4183541 to your computer and use it in GitHub Desktop.
Save fnielsen/4183541 to your computer and use it in GitHub Desktop.
Simplest sentiment analysis in Python with AFINN
#!/usr/bin/python
#
# (originally entered at https://gist.github.com/1035399)
#
# License: GPLv3
#
# To download the AFINN word list do:
# wget http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/6010/zip/imm6010.zip
# unzip imm6010.zip
#
# Note that for pedagogic reasons there is a UNICODE/UTF-8 error in the code.
import math
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# AFINN-111 is as of June 2011 the most recent version of AFINN
filenameAFINN = 'AFINN/AFINN-111.txt'
afinn = dict(map(lambda (w, s): (w, int(s)), [
ws.strip().split('\t') for ws in open(filenameAFINN) ]))
# Word splitter pattern
pattern_split = re.compile(r"\W+")
def sentiment(text):
"""
Returns a float for sentiment strength based on the input text.
Positive values are positive valence, negative value are negative valence.
"""
words = pattern_split.split(text.lower())
sentiments = map(lambda word: afinn.get(word, 0), words)
if sentiments:
# How should you weight the individual word sentiments?
# You could do N, sqrt(N) or 1 for example. Here I use sqrt(N)
sentiment = float(sum(sentiments))/math.sqrt(len(sentiments))
else:
sentiment = 0
return sentiment
if __name__ == '__main__':
# Single sentence example:
text = "Finn is stupid and idiotic"
print("%6.2f %s" % (sentiment(text), text))
# No negation and booster words handled in this approach
text = "Finn is only a tiny bit stupid and not idiotic"
print("%6.2f %s" % (sentiment(text), text))
@murali6688
Copy link

Im getting 0 for all sentences, please help

@murali6688
Copy link

its working thank you

@MZeeshan7474
Copy link

File "C:\Users\Zeeshan Mirza\Desktop\AFINN\AFINN\afinn.py", line 21
afinn = dict(map(lambda (w, s): (w, int(s)), [

please tell me how can i handle it ?

@fnielsen
Copy link
Author

fnielsen commented May 6, 2021

@ZeeshanMirza74 Your errors is insufficient to determine what you problem is. You probably need to set the filename filenameAFINN to the appropriate one.

If you are using Python you might also try the afinn Python package https://pypi.org/project/afinn/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment