简体   繁体   English

将使用Python从Twitter检索到的数据保存到文本文件?

[英]Saving Data retrieved from Twitter utilizing Python to a text file?

Hello all I am currently working on doing some research and was utilizing the twitter api to collect information. 您好,我目前正在做一些研究,并且正在使用twitter api收集信息。 I wrote some code to query for specific tweets in python and would like to save the results to a text file, yet my code is only returning the last tweet of the tweets returned can anyone tell me how I may correct this and what's wrong? 我写了一些代码来查询python中的特定推文,并想将结果保存到文本文件中,但是我的代码仅返回所返回推文中的最后一条推文,任何人都可以告诉我如何纠正此错误,这是怎么回事? The following is a sample of my code in Python only saving the last tweet instead of all of the returned tweets: 以下是我在Python中的代码示例,仅保存最后的tweet而不是所有返回的tweet:

u = urllib2.urlopen('http://search.twitter.com/search.json?geocode=29.762778,-95.383056,10.0mi&page=1&rpp=10')
datares = json.load(u)
pprint.pprint(datares)
for tweet in datares['results']:
  print tweet['text']
  archive=tweet['text']
  unicodedata.normalize('NFKD', archive).encode('ascii','ignore')
  with codecs.open('HTXtweets.txt',mode='w', encoding='utf-8',errors='replace') as cache:
    cache.write(archive)
    cache.closed

You're opening the file in each iteration of the loop through the results. 您将在循环的每次迭代中通过结果打开文件。 This recreates it from scratch each time. 每次都从头开始重新创建它。

You should open it before the loop - you don't need to close it at the end, as that will happen automatically when the with statement finishes. 您应该在循环之前将其打开-您无需在结束时将其关闭,因为在with语句结束时,这将自动发生。

The reason for this is that you open the file for writing in each iteration. 这样做的原因是,您打开文件以在每次迭代中进行写入。 This will replace existing content in the file. 这将替换文件中的现有内容。 Try using the flag 'a' (as in append) instead when opening the file. 打开文件时,请尝试使用标志'a' (如附录中所示)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM