0

I'm testing a sample code from [https://finnaarupnielsen.wordpress.com/2011/06/20/simplest-sentiment-analysis-in-python-with-af/] It shows nothing else but a Syntax error on Lambda. When I try running the code on 2.7 it shows no errors. Why is this?

#!/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))
5
  • omg thank you. i was losing my mind as to why this wasn't working. thank you for responding very fast :) how do you suggest I modify the line " ws.strip().split('\t') for ws in open(filenameAFINN) ]))" ? Commented Dec 13, 2016 at 16:58
  • cuz if i replace all "ws" with "x" it'll show that: TypeError: object of type 'map' has no len() >>> Commented Dec 13, 2016 at 17:01
  • You don't need to replace ws with anything, should work asis. Commented Dec 13, 2016 at 17:57
  • You can also look into the afinn Python package (on PyPI or GitHub). This package should work on a number of versions of Python, including 3.4. github.com/fnielsen/afinn Commented Dec 14, 2016 at 9:05
  • Thank you! Sorry for responding late -- Will try as soon as possible Commented Dec 16, 2016 at 17:55

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.