【发布时间】:2018-08-24 21:40:26
【问题描述】:
我正在尝试使用 Tweepy 获取搜索查询的 JSON 格式,但有一个问题:我的最终 JSON 文件是任何程序都无法读取的格式,在检查文件后,脚本似乎写入了所有数据没有任何正确的间距(对于 JSON 格式)
所以,我一直在试图寻找问题,但我真的找不到任何与脚本有关的问题。有人知道写作部分有什么问题吗?
这是脚本:
def write_tweets(tweets, filename):
''' Function that appends tweets to a file. '''
with open(filename, 'a') as f:
for tweet in tweets:
json.dump([tweet._json], f)
f.write('\n')
。 . . .
for search_phrase in search_phrases:
print('Search phrase =', search_phrase)
''' other variables '''
name = search_phrase.split()[0]
json_file_root = name + '/' + name
os.makedirs(os.path.dirname(json_file_root), exist_ok=True)
read_IDs = False
# open a file in which to store the tweets
if max_days_old - min_days_old == 1:
d = dt.datetime.now() - dt.timedelta(days=min_days_old)
day = '{0}-{1:0>2}-{2:0>2}'.format(d.year, d.month, d.day)
else:
d1 = dt.datetime.now() - dt.timedelta(days=max_days_old-1)
d2 = dt.datetime.now() - dt.timedelta(days=min_days_old)
day = '{0}-{1:0>2}-{2:0>2}_to_{3}-{4:0>2}-{5:0>2}'.format(
d1.year, d1.month, d1.day, d2.year, d2.month, d2.day)
json_file = json_file_root + '_' + day + '.json'
if os.path.isfile(json_file):
print('Appending tweets to file named: ',json_file)
read_IDs = True
# authorize and load the twitter API
api = load_api()
# set the 'starting point' ID for tweet collection
if read_IDs:
# open the json file and get the latest tweet ID
with open(json_file, 'r') as f:
lines = f.readlines()
max_id = json.loads(lines[-1])['id']
print('Searching from the bottom ID in file')
else:
# get the ID of a tweet that is min_days_old
if min_days_old == 0:
max_id = -1
else:
max_id = get_tweet_id(api, days_ago=(min_days_old-1))
# set the smallest ID to search for
since_id = get_tweet_id(api, days_ago=(max_days_old-1))
print('max id (starting point) =', max_id)
print('since id (ending point) =', since_id)
【问题讨论】:
-
Waaay 代码太多。请发Minimal, complete and verifiable example。
-
对不起!让我裁剪我需要检查的部分!
-
是什么让您认为“脚本写入所有数据时没有任何正确的间距(对于 Json 格式)”? JSON 的唯一标准是针对文件中的单个 JSON 文档。有些程序和 API 使用多个 JSON 文档的流,但它们都做不同的事情。有些要求您的 JSON 没有非转义的行终止符,并且在每个结束符之后都有一个换行符。或者他们只禁止
\r并要求\r\n\r\n作为分隔符。或者他们只是假设 JSON 是自定界的(如果您使用旧的“文档”定义,其中顶层必须是对象或数组)。以此类推。 -
那么,你想把它传递给哪个程序,它需要在一个文件中包含多个 JSON 文档,它在抱怨什么?
-
这仍然是太多的代码——但现在它显然完全丢失了所有相关的代码。当然很难确切地知道什么是相关的,但是您在询问“写作部分”并且编辑版本中没有
json.dump或其他写作代码……请阅读@roganjosh 链接到的帮助;它解释了你应该和不应该包括的内容。
标签: python json twitter format tweepy