我正在使用snowball词干分析器来处理文档中的单词,如下面的代码片段所示。
stemmer = EnglishStemmer()
# Stem, lowercase, substitute all punctuations, remove stopwords.
attribute_names = [stemmer.stem(token.lower()) for token in wordpunct_tokenize(re.sub('[%s]' % re.escape(string.punctuation), '', doc)) if token.lower() not in stopwords.words('english')]当我在Eclipse中使用PyDev对文档运行此命令时,没有收到任何错误。当我在终端(Mac OSX)中运行它时,我收到以下错误。有人能帮帮忙吗?
File "data_processing.py", line 171, in __filter__
attribute_names = [stemmer.stem(token.lower()) for token in wordpunct_tokenize(re.sub('[%s]' % re.escape(string.punctuation), '', doc)) if token.lower() not in stopwords.words('english')]
File "7.3/lib/python2.7/site-packages/nltk-2.0.4-py2.7.egg/nltk/stem/snowball.py", line 694, in stem
word = (word.replace(u"\u2019", u"\x27")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 7: ordinal not in range(128)发布于 2013-05-22 23:48:11
这在PyDev中是有效的,因为它将Python本身配置为在控制台的编码(通常是UTF-8)中工作。
如果你进入运行配置(run > run configurations),那么你可以在PyDev中重现同样的错误,然后在'common‘选项卡上说你想要的是ascii编码。
这是因为您的单词是一个字符串,并且您将替换为unicode字符。
我希望下面的代码能给你一些启发:
这一切都考虑到了ascii作为默认编码:
>>> 'íã'.replace(u"\u2019", u"\x27")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa1 in position 0: ordinal not in range(128)但是如果全部用unicode完成,它就能正常工作(如果您希望处理字符串而不是unicode,则可能需要将其编码回预期的编码)。
>>> u'íã'.replace(u"\u2019", u"\x27")
u'\xed\xe3'因此,您可以在替换之前将字符串设置为unicode
>>> 'íã'.decode('cp850').replace(u"\u2019", u"\x27")
u'\xed\xe3'或者您可以对替换字符进行编码
>>> 'íã'.replace(u"\u2019".encode('utf-8'), u"\x27".encode('utf-8'))
'\xa1\xc6'但是请注意,您必须知道您在任何地方使用的实际编码是什么(因此,尽管我在示例中使用了cp850或utf-8,但它可能与您必须使用的编码有所不同)
发布于 2013-09-23 20:05:38
正如Fabio所说,这是因为Pydev更改了Python的默认编码。你知道,有三种可能的解决方案:
在Pydev之外测试您的代码
Pydev将对您隐藏编码问题,直到您在Eclipse之外运行代码。因此,不要使用Eclipse的"run“按钮,而是从shell测试您的代码。
不过,我不建议这样做:这意味着您的开发环境将与您的运行环境不同,这只会导致出错。
更改Python的默认编码
你可以改变Python的环境来适应Pydev的环境,这在this question ( How to set the default encoding to UTF-8 in Python? )中有讨论。
This answer会告诉你怎么做,而this one会告诉你为什么不应该这样做。
长话短说,不要。
停止Pydev更改Python的默认编码
如果你使用的是Python 2,那么Python的默认编码应该是ascii。因此,与其通过黑客攻击让Pydev的环境着火,不如强迫Pydev“行为”。here讨论了如何做到这一点。
https://stackoverflow.com/questions/16678500
复制相似问题