我正在使用雪球词干来阻止文档中的单词,如下面的代码片段所示。
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)
答案 0 :(得分:4)
这适用于PyDev,因为它将Python本身配置为在控制台的编码中工作(通常是UTF-8)。
如果你进入运行配置(运行>运行配置),你可以在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,但它可能与您必须使用的编码不同)
答案 1 :(得分:0)
正如Fabio所说,这是因为Pydev改变了Python的默认编码。你知道的,有三种可能的解决方案:
在Pydev之外测试您的代码
Pydev将隐藏您的编码问题,直到您在Eclipse之外运行代码。因此,不要使用Eclipse的“运行”按钮,而是从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。