我想使用Stanford来解析具有Python界面的中文文本。我的代码如下:
#!~/anaconda/bin/python
# -*- coding: utf-8 -*-
from nltk.parse import stanford
parser = stanford.StanfordParser(path_to_jar='/home/stanford-parser/stanford-parser.jar', path_to_models_jar='/home/stanford-parser/stanford-parser-3.3.0-models.jar',model_path="/home/stanford-parser/chinesePCFG.ser.gz",encoding='utf8')
sentences = parser.raw_parse_sents(("我 是 中国 人。", "他 来自 美国。"))
print sentences 但是,当我试图运行此代码时,会出现解码错误。
Traceback (most recent call last):
File "/home/test.py", line 8, in <module>
sentences = parser.raw_parse_sents(("我 是 中国人。", "他 来自 美国。"))
File "/home/anaconda/lib/python2.7/site-packages/nltk/parse/stanford.py", line 176, in raw_parse_sents
return self._parse_trees_output(self._execute(cmd, '\n'.join(sentences), verbose))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)我不知道为什么会发生这样的错误,因为我的代码是由utf-8作为第二行编辑的。有人能帮我解释一下并解决吗?我真的需要堆栈溢出社区的帮助。
发布于 2015-08-12 06:58:45
解析器需要一个unicode对象(实际上您在创建时告诉它,您将使用以UTF-8编码的数据。但是,作为参数发送给它的只是简单的字符串,基本上是字节序列(在Python2.x中)。您可以通过在字符串前加上u (例如u"我 是 中国 人" )来创建u"我 是 中国 人"
>>> word = u"我 是 中国 人"
>>> type(word)
<type 'unicode'>
>>> print word
我 是 中国 人并将现有的普通字符串转换为unicode对象:
>>> word = "我 是 中国 人"
>>> type(word)
<type 'str'>
>>> unicode_word = unicode(word, encoding='utf8')
>>> type(unicode_word)
<type 'unicode'>如果这类事情给您带来麻烦,我强烈建议您阅读Python中的Unicode方法部分,这可能会使一切变得更加清楚。
奖金
若要将表示Unicode转义序列的普通字符串转换为Unicode字符串,请使用编码。
>>> type('\u6211')
<type 'str'>
>>> len('\u6211')
6
>>> converted = '\u6211'.decode('unicode_escape')
>>> type(converted)
<type 'unicode'>
>>> len(converted)
1
>>> print converted
我https://stackoverflow.com/questions/31919980
复制相似问题