2017-05-28 47 views
-1

當我運行代碼時,我想將其保存爲輸出。不能保存到像「運行」結果的「txt文件」

但我的代碼存儲方式不同。

我該如何解決?感謝您的建議。

「運行結果」=

1:{ '文':「今天是星期天! https // abcd'}

2:{'text':'hi !!! \ nhi !!! \ nhi !!! HTTPS // ABCD}

「的文本文件保存結果」=

今天是星期天! https // abcd

嗨!

嗨!

嗨! https // abcd

import tweepy 
import time 
import os 
import json 
import simplejson 


search_term = '' 



lat = "" 
lon = "" 
radius = "" 


API_key = "" 
API_secret = "" 
Access_token = "" 
Access_token_secret = "" 

location = "%s,%s,%s" % (lat, lon, radius) 
auth = tweepy.OAuthHandler(API_key, API_secret) 
auth.set_access_token(Access_token, Access_token_secret) 

api = tweepy.API(auth) 

c=tweepy.Cursor(api.search, 
       q="{}".format(search_term), 
       rpp=100, 
       geocode=location, 
       include_entities=False) 

wfile = open("test1.txt", mode='w', encoding='utf8') 
data = {} 
i = 1 
for tweet in c.items(): 

    data['text'] = tweet.text 
    print(i, ":", data) 
    wfile.write(data['text']+'\n') 
    time.sleep(0.35) 
    i += 1 

wfile.close() 

回答

0

你需要澄清你的問題,我猜沒有人真的知道你想要達到什麼目的。你想在你的文本文件中輸入字典的「json like」嗎?給我們一個例子,你的文件的內容應該如何。

我給出一個猜測,也許你只是想要你的字典的字符串表示,你可以通過調用str(data)data.__str__()來獲得字符串表示。

wfile = open("test1.txt", mode='w', encoding='utf8') 
data = {} 
i = 1 
for tweet in c.items(): 

    data['text'] = tweet.text 
    print(i, ":", data) 
    wfile.write(str(data) +'\n') 
    time.sleep(0.35) 
    i += 1 

wfile.close()