2016-07-26 36 views
0

我使用此代码从我在文件内写入的Feed获取推文。 当我读取文件,并尝试json的行我总是得到一个错误。json.loads或json.load()发布结果

def SearchTwt(api): 
    os.chdir('/Users/me/Desktop') 
    SearchResult = api.search(q='market',lang='en',rpp=20) 
    text_file = open("TweetOut.txt", "w") 
    for tw in SearchResult: 
     text_file.write(str(tw)) 
     print(str(tw)) 
    text_file.close() 

我阅读该文件:

def readfile(): 
    tweets_data = [] 
    os.chdir('/Users/me/Desktop') 
    file = open("TweetOut.txt", "r") 

    for line in file: 
     parts = line.split("Status(") 

     print (len(parts)) 
     for part in parts: 
      tweet = 'Status('+part 
      if len(tweet) > 10: 
       tweetj = json.loads(tweet) 
       #tweets_data.append(tweet) 
       print(tweet) 
    file.close() 

可能这是不对的,以填补S​​TR(TW)的文件?是的,我在阅读过程中重建了字符串,因为我认为推文就是这样开始的。所以可能是另一个错误。

我尝试了很多其他的选择。

错误: 从无 json.decoder.JSONDecodeError提高JSONDecodeError( “期待值”,S,err.value):期待值:第1行第1列(CHAR 0)

文件开始等这(根据堆栈问题编辑url): Status(source ='SocialFlow',id = 757991135465857024,in_reply_to_status_id = None,is_quote_status = False,entities = {'hashtags':[],'user_mentions':[],'符号 ':[], '网址':[{' URL“: '', 'expanded_url': '', 'DISPLAY_URL':

回答

2

的文件是不是有效的JSON应该是这样的

{ 
    "source": "SocialFlow", 
    "id":"757991135465857024", 
    ... 
    "entities": { 
    "hashtags": [], 
    "user_mentions": [], 
    ... 
    } 
} 

因为它不是有效的json,你必须以不同的方式解析它,或者确保在保存文件时将它写为json。

+0

好吧,我将文件另存为txt。我会尝试这一个:http://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file-in-python – pierre

+0

没有远远与此代码:json。 dump(SearchResult,text_file,ensure_ascii = False)引发TypeError(repr(o)+“不是JSON序列化”) – pierre

+0

我没有给你代码......这只是一个观察,你的JSON是错误的。另外我不知道你存储的所有JSON,所以我不能帮你用实际的代码......这就是为什么我用三个点来表示填充空白 – MiltoxBeyond