Python NLTK: SyntaxError: Non-ASCII character ‘\xc3’ in file (Sentiment Analysis -NLP)


I am playing around with NLTK to do an assignment on sentiment analysis. I am using Python 2.7. NLTK 3.0 and NumPy1.9.1 version.

This is the code :

__author__ = 'karan'
import nltk
import re
import sys

def main():
    # getting the stop words
    stopWords = open("english.txt","r");
    stop_word =;
    AllStopWrd = []
    for wd in stop_word:
    print("stop words-> ",AllStopWrd);

    # sample and also cleaning it
    tweet1= 'Love, my new toyí ½í¸í ½í¸#iPhone6. Its good'
    print("old tweet-> ",tweet1)
    tweet1 = tweet1.lower()
    tweet1 = ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",tweet1).split())
    tw = tweet1.split()

    sentences = nltk.word_tokenize(tweet1)
    print("tokenized ->", sentences)

    #remove stop words
    Otweet =[]
    for w in tw:
        if w not in AllStopWrd:
    print("sans stop word-> ",Otweet)

    # get taggers for neg/pos/inc/dec/inv words
    taggers ={}
    negWords = open("neg.txt","r");
    neg_word =;
    print("ned words-> ",neg_word)
    posWords = open("pos.txt","r");
    pos_word =;
    print("pos words-> ",pos_word)
    incrWords = open("incr.txt","r");
    inc_word =;
    print("incr words-> ",inc_word)
    decrWords = open("decr.txt","r");
    dec_word =;
    print("dec wrds-> ",dec_word)
    invWords = open("inverse.txt","r");
    inv_word =;
    print("inverse words-> ",inv_word)
    for nw in neg_word:
    for pw in pos_word:
    for iw in inc_word:
    for dw in dec_word:
    for ivw in inv_word:
    print("tagger-> ",taggers)

    # get parts of speech
    posTagger = [nltk.pos_tag(tw)]
    print("posTagger-> ",posTagger)


This is the error that I am getting when running my code:

SyntaxError: Non-ASCII character '\xc3' in file C:/Users/karan/PycharmProjects/mainProject/ on line 19, but no encoding declared; see for details

How do I fix this error?

I also tried the code using Python 3.4.2 and with NLTK 3.0 and NumPy 1.9.1 but then I get the error:

Traceback (most recent call last):
  File "C:/Users/karan/PycharmProjects/mainProject/", line 80, in <module>
  File "C:/Users/karan/PycharmProjects/mainProject/", line 72, in main
    posTagger = [nltk.pos_tag(tw)]
  File "C:\Python34\lib\site-packages\nltk\tag\", line 100, in pos_tag
    tagger = load(_POS_TAGGER)
  File "C:\Python34\lib\site-packages\nltk\", line 779, in load
    resource_val = pickle.load(opened_resource)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcb in position 0: ordinal not in range(128)

Best Answer

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=