从pymongo.objectid导入ObjectId ImportError:没有名为objectid的模块

从pymongo.objectid导入ObjectId ImportError:没有名为objectid的模块

问题描述:

我制作了一个python代码,该代码从Mongo集合中获取称为Tweets的tweets.我不会只获取对象文本并添加一个名为情感"的对象.

I made an python code that fetch tweets from Mongo collection called Tweets. I wan't to fetch only the object text and add an additional object called Sentiment.

当我遍历Tweets并将json对象解析为字符串时,出现错误:

When i loop through the Tweets and parse the json object to a string i get the error :

来自pymongo.objectid import ObjectId ImportError:没有名为objectid的模块

因此,我使用以下代码

import pymongo
import nltk
import json
from json import JSONEncoder
from pymongo import MongoClient
from pymongo.objectid import ObjectId

#JSON Encoder
class MongoEncoder(JSONEncoder):
    def default(self, obj, **kwargs):
        if isinstance(obj, ObjectId):
            return str(obj)
        else:            
            return JSONEncoder.default(obj, **kwargs)

#Mongo Settings
client = MongoClient()
db = client.Sentiment
Tweets = db.Tweet
TweetTraining = db.TweetTraining

#GET TEXT_TAG FROM TWEET
for tweet in Tweets.find({"lang":"nl"},{"text"}):
  print json.dumps(tweet, cls=MongoEncoder)

我希望你能帮助我.非常感谢

I hope that you can help me out. Many thanks

Erik

文件顶部的导入之一不正确. ObjectId应该从bson.objectid而不是pymongo.objectid

One of the imports at the top of your file is incorrect. ObjectId should be loaded from bson.objectid instead of pymongo.objectid

from bson.objectid import ObjectId

这里是pymongo文档的链接,用于按ObjectId查询

Here is a link to the pymongo documentation for querying by ObjectId

PyMongo-按ObjectId查询