使用pymongo在MongoDB中存储推文

时间:2016-08-23 11:28:15

标签: python mongodb

我正在尝试将推文直接从Twitter保存到MongoDB以便稍后检索,但我不断收到有关json的错误消息。有人请帮忙!以下是包含错误消息的示例代码。

searcher = keywordSearcher('','','') ## this is an object class
client = MongoClient('localhost', 27017)
db = client.test_dbase  ## connect to database twitter
collection = db.rio_olympics ## create a collection object
result = searcher.getTwitterComment('Olympics 2016', '21 August 2016', 2) ## this is where I query Twitter Search API

py_dict = json.load(result)
post_id = collection.insert_many(py_dict)

错误消息:

Traceback (most recent call last):
  File "/home/edidiong/myWorkSpace/keywordSearchTest.py", line 12, in <module>
    class keywordSearchTest:
  File "/home/edidiong/myWorkSpace/keywordSearchTest.py", line 45, in keywordSearchTest
    py_dict = json.load(result)
  File "/usr/lib/python2.7/json/__init__.py", line 287, in load
    return loads(fp.read(),
  AttributeError: 'dict' object has no attribute 'read'

2 个答案:

答案 0 :(得分:1)

你的searcher.getTwitterComment会返回字典,而不是json。

这就是您收到此错误的原因,可能已调用json.load()

答案 1 :(得分:1)

错误消息表明您正在尝试load字典对象。这意味着您已经有了一个字典对象。即使它确实有效,我也不确定json.load的重点是什么。

所以你可以这样做:

py_dict = searcher.getTwitterComment("Olympics 2016", '21 August 2016', 2)
post_id = collection.insert_many(py_dict)