TypeError: must be unicode, not str in NLTK

TypeError: must be unicode, not str in NLTK

我正在使用 python2.7、nltk 3.2.1 和 python-crfsuite 0.8.4。我正在关注此页面:http://www.nltk.org/api/nltk.tag.html?highlight=stanford#nltk.tag.stanford.NERTagger 用于 nltk.tag.crf 模块。

首先我只是 运行 这个

from nltk.tag import CRFTagger
ct = CRFTagger()
train_data = [[('dfd','dfd')]]
ct.train(train_data,"abc")

我也试过了

f = open("abc","wb")
ct.train(train_data,f)

但我收到以下错误,

  File "C:\Python27\lib\site-packages\nltk\tag\crf.py", line 129, in <genexpr>
    if all (unicodedata.category(x) in punc_cat for x in token):
TypeError: must be unicode, not str

在 Python 2 中,正则引号 '...'"..." 创建字节字符串。要获取 Unicode 字符串,请在字符串前使用 u 前缀,例如 u'dfd'.

要从文件中读取,您需要指定编码。有关选项,请参阅 Backporting Python 3 open(encoding="utf-8") to Python 2;最直接的,将 open() 替换为 io.open().

要转换现有的字符串,使用unicode()方法;尽管通常情况下,您也需要使用 decode() 并提供编码。

对于(很多)更多细节,推荐 Ned Batchelder 的 "Pragmatic Unicode" 幻灯片,如果不是完全强制阅读的话; http://nedbatchelder.com/text/unipain.html