【问题标题】:sentiment_analyser error: 'bytes' object has no attribute 'encode' using情感分析器错误:“字节”对象没有属性“编码”使用
【发布时间】:2017-09-15 04:10:49
【问题描述】:

从事一个使用 nltk 对股票进行情绪分析的项目。我已经通过 GH 进行了搜索,并没有发现与 sentimaent_analysisr 或流行度分数调用类似的东西。

我还查看了Python 3.4 - 'bytes' object has no attribute 'encode',它不是重复的,因为我没有调用 bcrypt.gensalt().encode('utf-8')。虽然它确实暗示了某些类型错误的问题。

谁能帮忙解决这个错误?

我得到错误:

/lib/python3.5/site-packages/nltk/sentiment/vader.py in init(自我,文本) 154 def 初始化(自我,文本): 155 如果不是 isinstance(text, str): --> 156 文本 = str(text.encode('utf-8')) 第157章 158 self.words_and_emoticons = self._words_and_emoticons()

AttributeError: 'bytes' 对象没有属性 'encode'

df_stocks.head(5) 的数据框是:

            prices  articles
2007-01-01  12469   What Sticks from '06. Somalia Orders Islamist...
2007-01-02  12472   Heart Health: Vitamin Does Not Prevent Death ...
2007-01-03  12474   Google Answer to Filling Jobs Is an Algorithm...
2007-01-04  12480   Helping Make the Shift From Combat to Commerc...
2007-01-05  12398   Rise in Ethanol Raises Concerns About Corn as...                

代码如下,最后一行出现错误:

import numpy as np
import pandas as pd
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import subjectivity
from nltk.sentiment import SentimentAnalyzer
from nltk.sentiment.util import *from nltk.sentiment.vader import     SentimentIntensityAnalyzer
import unicodedata
for date, row in df_stocks.T.iteritems():
    sentence = unicodedata.normalize('NFKD', df_stocks.loc[date, 'articles']).encode('ascii','ignore')
    ss = sid.polarity_scores(sentence)

谢谢

【问题讨论】:

  • 似乎 df_stocks.loc[date, 'articles'] 不是 unicode str,df_stocks 是什么?
  • 我确实检查了那个,但我看不出它与上述内容的重复,因为我没有调用 bcrypt.gensalt().encode('utf-8') ...错误来自 NLTK 库
  • @aircraft 是的,你是对的......它是在 python 3 中键入 str ..所以目前正在将它映射到 unicode......我刚刚意识到代码是来自 python 2 的端口,可能导致此错误

标签: python python-3.x nltk


【解决方案1】:

unicodedata.normalize() docs开始,方法是将UNICODE字符串转换为通用格式字符串。

import unicodedata

print(unicodedata.normalize('NFKD', u'abcdあäasc').encode('ascii', 'ignore'))

它会得到:

b'abcdaasc'

所以,问题就在这里:df_stocks.loc[date, 'articles'] 不是 UNICODE 字符串。

【讨论】:

  • 是的,你是对的......它是在 python 3 中输入 str ..所以目前正在将它映射到 unicode......我刚刚意识到代码是一个端口来自可能导致此错误的 python 2
  • 很高兴为您提供帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
  • 2019-02-02
  • 2016-01-27
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多