首页 > 解决方案 > 标记句子时出现AttributeError

问题描述

当我尝试以下代码时:

tok_corp= [nltk.word_tokenize(sent.decode('utf-8')) for sent in corpus] 

我得到一个AttributeError

'float' 对象没有属性 'decode'

标签: pythonstringnltktokenizeattributeerror

解决方案


在将所有内容链接到单行之前,请尝试检查您的对象类型,例如

for sent in corpus:
    print(type(sent), sent)

你应该看到float里面有东西。

接下来str.decode('utf8')有点危险。如果您在 Python3 中,则 utf8 应该是默认值,因此如果您在 Python2 中,代码中的某处应该有一个open(),而不是在 Python2 中使用默认值,则不需要使用open()utf8 来指定编码io.open(),例如

import io

with io.open('somefile.txt', 'r', encoding='utf8') as fin:
    corpus = fin.read().split('\n')

这样,作为fin对象读取的所有内容默认都是str/unicode类型,因此不需要 `.decode('utf8') 。


推荐阅读