我正在学习Python两个月。我的目标是进行情绪分析!但是自学太难了,所以我想寻求帮助。
我从Twitter API收集数据,然后将数据放到记事本中。这太长了。 {created_at":"Fri Nov 03 03:28:33 +0000 2017", ~~ id, tweet, unicode}
我在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
谢谢!
答案 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)