【问题标题】:rest_api using tweets are not dumping into file in python使用推文的rest_api不会转储到python中的文件中
【发布时间】:2017-07-12 23:44:47
【问题描述】:

根据这段代码,一个文件应该包含 5000 条推文。但是没有任何东西进入文件并显示 json 序列化错误。

这里是代码

alltweet=[]
def rest_query_ex3():
    MAX_ID = None
    query = "(disease OR illness OR sickness)"
    file=open("tweetfile.txt", "a+")
    for it in range(50):
     tweets = myApi.search(q=query, count=100, max_id=MAX_ID)
     if tweets:
         MAX_ID = tweets[-1].id
         alltweet.extend(tweets)
    for tweet in alltweet:
        s=[tweet.text, tweet.id]
        file.write(json.dumps(s))
    file.close()

【问题讨论】:

  • 发布完整错误
  • Traceback(最近一次调用最后):文件“E:/datamining/hw3/datafetch.py​​”,第 40 行,在 rest_query_ex3() 文件“E:/datamining/hw3/datafetch .py”,第 36 行,在 rest_query_ex3 file.write(json.dumps(tweet)) 文件“C:\Python27\lib\json_init_.py”,第 244 行,在转储中返回 _default_encoder。编码(obj)文件“C:\Python27\lib\json\encoder.py”,第 207 行,编码块 = self.iterencode(o, _one_shot=True) 文件“C:\Python27\lib\json\encoder.py” py",第 270 行,在 iterencode 中返回 _iterencode(o, 0)
  • 此处的错误 ID 的其余部分
  • 文件 "C:\Python27\lib\json\encoder.py",第 184 行,默认引发 TypeError(repr(o) + " is not JSON serializable")
  • 我得到了解决方案,但我很想知道您对相同错误的建议

标签: python json python-2.7 python-3.x dataset


【解决方案1】:
alltweet=[]

def rest_query_ex3():
    MAX_ID = None
    geo = "42.6525,-73.7572,200mi"
    query = "(disease)"
    file =open("tweetfile.txt", "a+")
    for it in range(1):
     tweets = myApi.search(q=query, geocode=geo, count=5, max_id=MAX_ID)
     if tweets:
         MAX_ID = tweets[-1].id
         alltweet.extend(tweets)
         #print type(alltweet)   #this is list type object
    for tweet in alltweet:
        file.write(json.dumps(str(tweet))) 
#converting into string remove sthe serializable error without adding a new class
        file.write('\n\n')
if __name__ == '__main__':
    rest_query_ex3()

【讨论】:

    【解决方案2】:
    alltweet=[]
    
    def rest_query_ex3():
        MAX_ID = None
        geo = "42.6525,-73.7572,200mi"
        query = "(disease)"
        file =open("tweetfile.txt", "a+")
        for it in range(1):
         tweets = myApi.search(q=query, geocode=geo, count=5, max_id=MAX_ID)
         if tweets:
             MAX_ID = tweets[-1].id
             alltweet.extend(tweets)
             #print type(alltweet)   #this is list type object
        for tweet in alltweet:
            file.write(json.dumps(tweet._json)) 
    #converting into string remove sthe serializable error without adding a new class
            file.write('\n\n')
    if __name__ == '__main__':
        rest_query_ex3()
    

    【讨论】:

      猜你喜欢
      • 2017-07-12
      • 2016-01-03
      • 2017-09-30
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 2021-04-27
      • 2019-01-12
      • 2017-11-03
      相关资源
      最近更新 更多