Python NLTK:文件中的非ASCII字符'\xc3'(情感分析-NLP)出现语法错误。

76

我正在使用NLTK进行情感分析的作业实践。我使用的是Python 2.7版本,NLTK 3.0和NumPy 1.9.1版本。

以下是代码:

__author__ = 'karan'
import nltk
import re
import sys



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

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


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


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


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

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

main();

运行代码时出现了以下错误:

SyntaxError: Non-ASCII character '\xc3' in file C:/Users/karan/PycharmProjects/mainProject/sentiment.py on line 19, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

我该如何修复这个错误?

我也尝试了在Python 3.4.2和NLTK 3.0以及NumPy 1.9.1下运行代码,但是我得到了这个错误:

Traceback (most recent call last):
  File "C:/Users/karan/PycharmProjects/mainProject/sentiment.py", line 80, in <module>
    main();
  File "C:/Users/karan/PycharmProjects/mainProject/sentiment.py", line 72, in main
    posTagger = [nltk.pos_tag(tw)]
  File "C:\Python34\lib\site-packages\nltk\tag\__init__.py", line 100, in pos_tag
    tagger = load(_POS_TAGGER)
  File "C:\Python34\lib\site-packages\nltk\data.py", 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)
1个回答

201
将以下内容添加到文件顶部:# coding=utf-8 如果您访问错误中的链接,您就可以看到原因:
定义编码
如果没有给出其他编码提示,Python将默认使用ASCII作为标准编码。要定义源代码编码,必须在源文件中作为第一行或第二行放置一个魔法注释,例如:# coding=

1
好的,我在Python方面非常新手,我在同一行上使用了u"a"u"ã" - Iulian Onofrei
1
@IulianOnofrei,对于u"ã",您需要声明编码。您是否收到了错误信息? - Padraic Cunningham
1
@PadraicCunningham,我使用codecs.encode(u"ã", "utf-8")进行声明,错误来自于u"a" _(在添加了魔法注释之后,当然)_,现在一切都好了,谢谢。 - Iulian Onofrei
14
花了一个小时解决这个问题,答案是“一个神奇的评论”。我真是佩服自己。 - J-Dizzle
我添加了“魔法注释”,就没有出现那个错误了,但是os.path.isfile()说带有é的文件名不存在。讽刺的是,e字符在PEP错误链接的作者Marc-André Lemburg的名字中。 - user324747

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接