如何使用stanford解析器解决中文文本与python的解码

时间:2015-08-10 12:46:16

标签: python nlp decode encode stanford-nlp

我想用Stanford Parser用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 编辑的,就像第二行一样。谁能帮我解释一下并解决它?我真的需要stackoverflow社区的帮助。

1 个答案:

答案 0 :(得分:1)

解析器需要一个unicode对象(你在创建时实际告诉它你将使用以UTF-8编码的数据。但是,你作为参数发送给它的只是普通字符串,基本上只是字节序列(在Python 2.x中。您可以通过在u前加上字符串来创建unicode literals,例如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 HOWTO部分,它可能会使所有内容更加清晰。

加成

要将表示 Unicode转义序列的普通字符串转换为Unicode字符串,请使用'unicode_escape' encoding

>>> type('\u6211')
<type 'str'>
>>> len('\u6211')
6
>>> converted = '\u6211'.decode('unicode_escape')
>>> type(converted)
<type 'unicode'>
>>> len(converted)
1
>>> print converted
我
相关问题