TypeError:将tweet数据插入mysql Python 3时,'str'对象不可调用

时间:2018-05-23 15:49:23

标签: python mysql tweepy pymysql

这是我在MYSQL中插入推文数据的代码

import pymysql
import tweepy
import time
import json
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import pymysql.cursors

ckey= ''
csecret= ''
atoken=''
asecret=''

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='admin1234', db='mysql')
cur = conn.cursor()

class listener(StreamListener):

 def on_data(self, data):
        all_data = json.loads(data)
        tweet = all_data["text"]
        a=0
        #username = all_data["user"]["screen_name"]

        cur.execute("INSERT INTO tweet (textt) VALUES (%s)" (tweet))
        print (tweet)
        return True

def on_error(self, status):
    print (status)

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track = ["puasa"])

cur.close()
conn.close()

但我收到错误TypeError: 'str' object is not callable

追溯错误

Traceback (most recent call last):
  File "collect-sql.py", line 40, in <module>
    twitterStream.filter(track = ["puasa"])
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 450, in filter
    self._start(async)
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 364, in _start
    self._run()
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 297, in _run
    six.reraise(*exc_info)
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/six.py", line 693, in reraise
    raise value
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 266, in _run
    self._read_loop(resp)
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 327, in _read_loop
    self._data(next_status_obj)
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 300, in _data
    if self.listener.on_data(data) is False:
  File "collect-sql.py", line 30, in on_data
    cur.execute("INSERT INTO tweet (textt) VALUES (%s)" (tweet))
TypeError: 'str' object is not callable

1 个答案:

答案 0 :(得分:1)

您需要额外2个逗号:

cur.execute("INSERT INTO tweet (textt) VALUES (%s)", (tweet,))

第一个将查询字符串与参数分开,第二个将括号中的值转换为1个元素元组中的第一个元素(如果您只使用单个字符串而不是元组,则实际为would work,假设你只有一个参数,但从事物的外观来看,这并没有得到官方支持。

但是您在评论中提到的这个错误:

UnicodeEncodeError: 'latin-1' codec can't encode character '\u201c' in position 97: ordinal not in range(256)

表示您尝试将包含扩展字符集中的字符的unicode文本解释为latin-1

如果该字段已在内部定义(在您的mysql数据库中)为unicode,则可能需要指定连接时使用的字符集,例如:

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='admin1234', db='mysql', use_unicode=True, charset="utf8")

如果mysql中的字段不是像utf-8那样,那么我建议你改变或以其他方式重新定义数据库,以便为此列使用unicode字符。

https://dev.mysql.com/doc/refman/8.0/en/charset-mysql.html