从 tweepy API 请求数据时,错误 'dict' 对象不可调用

Error 'dict' object is not callable in requesting data from tweepy API

我尝试使用以下代码通过 tweepy API 检索推文,但检索到的 json 字典有错误。

代码:

import tweepy
from tweepy import OAuthHandler
from tweepy import Stream
import socket
import json
consumer_key="****"
consumer_secret="****"
access_token="****"
access_secret="****"


class TweetListener(Stream):
    def __init__(self, *args, csocket):    
        super().__init__(*args)
        self.client_socket = csocket
 
    def on_data(self, data):
        try:
            msg = json.loads(data)
            print(msg('text').encode('utf=8'))
            self.client_socket.send(msg('text').encode('utf=8'))
            return True
        except BaseException as e:
            print('Error %s'%str(e))
        return True
    def on_error(self, status):
        print(status)
        return True
def send_data(c_socket):
    twtr_stream = TweetListener(
        consumer_key, consumer_secret,
        access_token, access_secret,
        csocket=c_socket
    )
    twtr_stream.filter(track=['ETH'])
s = socket.socket()
host = "127.0.0.1"
port = 5000
s.bind((host,port))
print("Active port %s"%str(port))
s.listen(5)
c, addr = s.accept()
print("request from addr "+str(addr))
send_data(c)

send_data(c) 导致错误: Error 'dict' object is not callable 不断重复。

我有另一个与之关联的文件,这两个代码需要同时 运行。

代码:

from pyspark import SparkContext
from pyspark.streaming import StreamingContext
sc = SparkContext(appName='StreamingTwitterAnalysis')
sc.setLogLevel("ERROR")
ssc = StreamingContext(sc,10)
socket_stream = ssc.socketTextStream("127.0.0.1",5000)
lines = socket_stream.window(20)
hashtags = lines.flatMap(lambda text: text.split(" ")).filter(lambda word: word.lower().startwith("#")).map(lambda word: (word.lower(),1)).reduceByKey(lambda a,b:a+b)
dstream = hashtags.transform(lambda foo: foo.sortBy(lambda x:x[0].lower()).sortBy(lambda x:x[1].ascending==False))
dstream.pprint()
ssc.start()
ssc.awaitTermination()

笔记本片段:

第 1 行您在 pastebin 上上传的代码的 17,您加载了一个 JSON 对象 msg,它大概是一个 dict:

msg = json.loads(data)

第 1 行18 然后用字符串参数调用该对象:

print(msg('text').encode('utf=8'))

由于 dicts 不可调用,您会收到上述错误。 所以我假设你想访问那个名字的密钥:

print(msg['text'].encode('utf=8'))