我想在Python上使用out_file

时间:2017-11-09 02:04:27

标签: python json twitter tweepy

我正在学习Python两个月。我的目标是进行情绪分析!但是自学太难了,所以我想寻求帮助。

  1. 我从Twitter API收集数据,然后将数据放到记事本中。这太长了。 {created_at":"Fri Nov 03 03:28:33 +0000 2017", ~~ id, tweet, unicode}

  2. 我在IPython控制台(Spyder)上将数据转换为简单数据。这就像"Fri Nov 03 03:46:46 +0000 2017 @user blah blah [hash tags] time stamp"。然后我想再次将简单的数据放到记事本中。代码编写如下。如何更改out_file

    部分的代码
    try:
        import json
    
    except ImportError:
        import simplejson as json
    
    tweets_filename = 'C:/Users/ID500/Desktop/SA/Corpus/siri/siri_0.txt' #Not converted data
    
    tweets_file = open(tweets_filename, "r")
    
    for line in tweets_file:
        try:
            tweet = json.loads(line.strip())
            if 'text' in tweet:
                print (tweet['id'])
                print (tweet['created_at'])
                print (tweet['text'])
    
                print (tweet['user']['id'])
                print (tweet['user']['name'])
                print (tweet['user']['screen_name'])
    
                hashtags = []
                for hashtag in tweet['entities']['hashtags']:
                    hashtags.append(hashtag['text'])
                print(hashtags)
                out_file = open("C:/Users/ID500/Desktop/SA/Corpus/final/fn_siri_1.txt", 'a') # I want to put data to that path.
                out_file.write() # What can I write here?
                out_file.close()
    
        except:
            continue
    
  3. 谢谢!

1 个答案:

答案 0 :(得分:2)

您可以一次打开两个文件。不要在循环中打开一个

例如

open(tweets_filename) as tweets_file, open(output, "a") as out_file:
    for line in tweets_file:
        # parse the line here 
        out_file.write(line)