【发布时间】:2018-04-23 18:08:15
【问题描述】:
我是 Spyder 的 Python 用户。我想从记事本转换数据(推文),并将转换后的数据输出到其他记事本。它的代码是这样的。它将制作简单的数据,例如{created at: date, user_name, unicode..} -> user_name, data
try:
import json
except ImportError:
import simplejson as json
tweets_filename = 'C:/Users/siri_0.txt' #unconverted 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)
output = "C:/Users/fn_siri.txt"
#I want to put the converted data here.
out_file = open(output, 'a')
out_file.write(line)
out_file.close()
except:
continue
很遗憾,C:/Users/fn_siri.txt 只能包含“未转换的数据”。如何更改包含转换后数据的代码?
【问题讨论】:
-
您正在遍历
tweets_file中的所有line,然后执行大量printing,然后将原始line值存储到您的输出文件中。与其将信息打印到屏幕上,不如将它们作为文本字符串存储在变量中并将它们保存到文件中。那是你需要帮助的地方吗? -
我解决了。谢谢:)