【问题标题】:TypeError: must be unicode, not str in NLTKTypeError:必须是 unicode,而不是 NLTK 中的 str
【发布时间】:2016-11-18 10:41:24
【问题描述】:

我正在使用 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

【问题讨论】:

  • 你能告诉我们“abc”中的数据吗?根据错误,这就是您的问题...

标签: python nltk crf


【解决方案1】:

在 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

【讨论】:

    猜你喜欢
    • 2019-03-15
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多