【问题标题】:How to solve 'numpy.float64' object has no attribute 'encode' in python 3如何解决'numpy.float64'对象在python 3中没有属性'encode'
【发布时间】:2017-12-07 10:46:46
【问题描述】:

我正在尝试在 twitter 中对不同汽车品牌进行情绪分析,为此我使用 python 3。运行代码时,我得到以下异常

Traceback (most recent call last):
File "C:\Users\Jeet Chatterjee\NLP\Maruti_Toyota_Marcedes_Brand_analysis.py", line 55, in <module>
x = str(x.encode('utf-8','ignore'),errors ='ignore')
AttributeError: 'numpy.float64' object has no attribute 'encode'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Jeet Chatterjee\NLP\Maruti_Toyota_Marcedes_Brand_analysis.py", line 62, in <module>
tweets.set_value(idx,column,'')
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\pandas\core\frame.py", line 1856, in set_value
engine.set_value(series._values, index, value)
 File "pandas\_libs\index.pyx", line 116, in pandas._libs.index.IndexEngine.set_value (pandas\_libs\index.c:4690)
File "pandas\_libs\index.pyx", line 130, in pandas._libs.index.IndexEngine.set_value (pandas\_libs\index.c:4578)
File "pandas\_libs\src\util.pxd", line 101, in util.set_value_at (pandas\_libs\index.c:21043)
  File "pandas\_libs\src\util.pxd", line 93, in util.set_value_at_unsafe (pandas\_libs\index.c:20964)
 ValueError: could not convert string to float: 

我不知道如何在 python 3 中表示编码。这是我的代码

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from textblob import TextBlob
import json
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#regular expression in python
import re

#data corpus
tweets_data_path = 'carData.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
    try:
        tweet = json.loads(line)
        tweets_data.append(tweet)
    except:
        continue
#creating panda dataset        
tweets = pd.DataFrame()
index = 0
    for num, line in enumerate(tweets_data):
  try:

     print (num,line['text'])

     tweets.loc[index,'text'] = line['text']
     index = index + 1 
  except:
         print(num, "line not parsed")
         continue

   def brand_in_tweet(brand, tweet):
       brand = brand.lower()
       tweet = tweet.lower()
       match = re.search(brand, tweet)
       if match:
        print ('Match Found')
        return brand
    else:
        print ('Match not found')
        return 'none'
for index, row in tweets.iterrows():
temp = TextBlob(row['text'])
tweets.loc[index,'sentscore'] = temp.sentiment.polarity

  for column in tweets.columns:
  for idx in tweets[column].index:
    x = tweets.get_value(idx,column)
    try:
        x = str(x.encode('utf-8','ignore'),errors ='ignore')          
        if type(x) == unicode:
            str(str(x),errors='ignore')
        else: 
            df.set_value(idx,column,x)
    except Exception:
        print ('encoding error: {0} {1}'.format(idx,column))
        tweets.set_value(idx,column,'')
        continue
tweets.to_csv('tweets_export.csv')

if __name__=='__main__':

  brand_in_tweet()

我已经发布了完整的代码,我没有得到任何关于这个错误的线索,以及如何解决这个问题。请提前帮助和感谢。

【问题讨论】:

    标签: python numpy tweepy sentiment-analysis


    【解决方案1】:

    这行有问题:

     x = str(x.encode('utf-8','ignore'),errors ='ignore')  
    

    x 是一个numpy.float64。该代码试图首先将其编码为 utf8,然后将其转换为字符串。但这是错误的方法,因为只能对字符串进行编码。先将其转为字符串,然后对字符串进行编码:

     x = str(x).encode('utf-8','ignore')
    

    【讨论】:

    • 感谢您的回答,异常已删除,我正在处理另一个异常 NameError: name 'df' is not defined,如何解决这个问题?
    • 您的代码显示df.set_value(idx,column,x),但您没有在任何地方定义df。我的猜测是它应该是一个熊猫数据框。您的代码仅定义的唯一数据框是tweets,因此该行可能应该是tweets.set_value(idx,column,x)。否则你需要df=pd.DataFrame()。我不能告诉你是哪个,因为我真的不明白你想做什么。
    • 感谢您的即时回复,您的回答非常有帮助,所以基本上我正在尝试比较汽车铃木,丰田,马塞德斯的3个布拉德,我想比较三个品牌的受欢迎程度。 carData.txt 包含关于这三个品牌的推文,就是这样。
    • 错误信息非常明确。它告诉你在第 58 行 df is not defined。根据您的描述,您只有一个数据框。所以你的代码应该一直调用它tweets,而不是有时tweets(在第23、48、52、61行),有时是df(在第58行)。我猜你有一些示例代码可以使用,并且在重命名变量方面不一致。
    • 是的,你是对的。我是这些领域的新手,并试图掌握这项技能
    【解决方案2】:

    问题:

    TypeError: 只能将 str(不是“numpy.float64”)连接到 str

    解决方案:

    例如:print("Accuracy" + str(accuracy_score(y_test, y_pred)))

    使用str() 连接int64string

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 2021-08-25
      • 2022-01-21
      • 2015-03-28
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 2013-08-05
      相关资源
      最近更新 更多