我正在尝试使用一个名为 MeCab 的程序,它对日语文本进行语法分析。我遇到的问题是它返回一个字节字符串,如果我尝试打印它,它会为几乎所有字符打印问号。但是,如果我尝试使用 .decode,它会抛出一个错误。这是我的代码:
#!/usr/bin/python
# -*- coding:utf-8 -*-
import MeCab
tagger = MeCab.Tagger("-Owakati")
text = 'MeCabで遊んでみよう!'
print text
result = tagger.parse(text)
print result
result = unicode(result, 'utf-8')
print result
这是我的输出:
MeCabで遊んでみよう!
MeCab �� �� ��んで�� �� ��う!
Traceback (most recent call last):
File "test.py", line 12, in <module>
result = unicode(result, 'utf-8')
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 6-7: invalid continuation byte
------------------
(program exited with code: 1)
Press return to continue
此外,我的终端能够正确显示日文字符。例如 print '日本语' 工作得很好。
有什么想法吗?
请您参考如下方法:
默认情况下,MeCab 不返回 UTF8。以下是来自以下链接的引述(通过谷歌翻译):
http://mecab.googlecode.com/svn/trunk/mecab/doc/index.html#charset
Unless otherwise specified, euc is used. If you would like to use the utf8 or shift-jis, change the charset with configure options dictionary, please rebuild the dictionary. Now, and shift-jis, dictionary of utf8 is created.
尝试 result = tagger.parse(text).decode('euc-jp')。
