代码之家  ›  专栏  ›  技术社区  ›  Tanmim Hanifa

如何分割推特流数据并将文本附加到csv文件?

  •  0
  • Tanmim Hanifa  · 技术社区  · 7 年前

    我有一个脚本,通过一个关键字过滤推特数据。它将数据流式传输到csv文件中,但推文附带了大量对象,例如Id、created\u at、文本、源等。

    我只需要将其中一些对象附加到csv文件,但即使在分割数据并仅附加文本对象之后,仍会出现一些附加了所有推文对象的推文。似乎转发的推文可以很好地拆分,但正常推文不会拆分。

    这是我的代码:

    ckey = 'xxxxxxxxxxxxxx'
    csecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    atoken = 'xxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    asecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    
    auth = OAuthHandler(ckey, csecret)
    auth.set_access_token(atoken, asecret)
    api = tweepy.API(auth)
    
    def dateRange(start, end):
        current = start
        while(end - current).days >=0:
            yield current
            current = current + datetime.timedelta(seconds = 1)
    
    
    class Tweetlistener(StreamListener):
        def on_data(self, data):
            startdate = datetime.datetime(2016,6,1)
            enddate = datetime.datetime(2016,6,7)
            for date in dateRange(startdate, enddate):
                try:
                    ##This is where I split the data
                    tweet = data.split(',"text":"')[1].split('","source')[0]
    
    
                    saveThis = str(time.time())+'::'+tweet
                    saveFile = open('test.csv', 'a')
                    saveFile.write(saveThis)
                    saveFile.write('\n')
                    return True
                except ValueError:
                    print("Something went wrong with streaming")
            saveFile.close()
    
        def on_error(self, status):
            print(status)
    
    
    twitterStream = Stream(auth, Tweetlistener(), secure = True)
    twitterStream.filter(track=['brexit'])
    

    这是csv文件中的结果 The first cell is a retweet and it splits as i intend it to, the cell below isn't a retweet and it appends all tweet objects

    第一个单元格是转发,它按我的意愿进行拆分,下面的单元格不是转发,它附加了所有推特对象。

    我怎样才能拆分数据并只附加文本、created\u at、retweet\u count、location、coordinates?

    编辑:

    这是每条推文中一行的原始数据(不是我的数据,只是我在网上找到的一个示例):

    {
     'contributors': None, 
     'truncated': False, 
     'text': 'My Top Followers in 2010: @tkang1 @serin23 @uhrunland @aliassculptor @kor0307 @yunki62. Find yours @ http://mytopfollowersin2010.com',
     'in_reply_to_status_id': None,
     'id': 21041793667694593,
     '_api': ,
     'author': ,
     'retweeted': False,
     'coordinates': None,
     'source': 'My Top Followers in 2010',
     'in_reply_to_screen_name': None,
     'id_str': '21041793667694593',
     'retweet_count': 0,
     'in_reply_to_user_id': None,
     'favorited': False,
     'retweeted_status': ,
     'source_url': 'http://mytopfollowersin2010.com', 
     'user': ,
     'geo': None, 
     'in_reply_to_user_id_str': None, 
     'created_at': datetime.datetime(2011, 1, 1, 3, 15, 29), 
     'in_reply_to_status_id_str': None, 
     'place': None
    

    }

    我希望我的数据是这种格式的每行一条推文:

    "created_at":Wed Aug 27 13:08:45 +0000 2008::"text"::Example tweet::"retweet_count":154::"favorite_count":200::"coordinates":[-75.14310264,40.05701649]
    

    其中“::”区分对象。

    2 回复  |  直到 7 年前
        1
  •  2
  •   jujuBee    7 年前

    您可以使用json解码器来完成这项工作

    import json
    required_fields = [u'text', u'created_at', u'retweet_count', u'place',  u'coordinates']
    
    ......
    
          data = data.decode('utf-8')
          json_data = json.loads(data) # this is dict
          tweet = '::'.join([i+':'+unicode(json_data[i]) for i in required_fields])
    
        2
  •  1
  •   OneCricketeer Gabriele Mariotti    7 年前

    我认为您得到的是JSON数据,所以很自然地,在Excel中将这样的文件视为CSV是个坏主意。

    这条线也是

    tweet = data.split(',"text":"')[1].split('","source')[0]
    

    相反,您需要解析密钥。例如

    import json, csv 
    
    def on_data(self, data):
        tweet = json.loads(data) 
        text = tweet["text"]
        source = tweet["source"]
        with open('test.csv', 'a') as f:
            writer = csv.writer(f)
            writer.writerow([text, source]) 
    

    这样做的目的不是基于某些字符串将字符串分割开来,而是实际使用其现有结构,然后按名称提取必要的字段

    旁注,就我个人而言,为每条消息打开和关闭一个文件在操作上很昂贵,因此我建议找到一种只在流启动和停止时才这样做的方法