PyMongo - `If` 在游标中无法正常工作

PyMongo - `If` doesn't work properly in cursor

我有一个MongoDB,文档是这样的: MongoDB collection Stucture

我有一个 txt 文件,其中包含一些词及其情感得分。

我想在MongoDB中找到这些词,但是为了某种关系,我想将这些文档的字段插入到一个新的集合中。

代码:

for w in words:
            print w
            cursor = db.collectionName.find({ 'surfaceStart': w })
        for document in cursor:
            relation = document['rel']
            word = document['surfaceEnd'].encode('utf-8')
            posnum = float(get_positive(cols))
            negnum = float(get_negative(cols))
            if (document['rel']).find('Synonym'):
                db.testcollection.insert ({ 'surfaceStart': w,'surfaceEnd': word,'Relation': relation, "pos": posnum, "neg": negnum })

            if (document['rel']).find('Antonym'):

                db.testcollection.insert ({ 'surfaceStart': w,'surfaceEnd': word,'Relation': relation, "pos": posnum, "neg": negnum })
            if (document['rel']).find('Related') or (document['rel']).find('Derived'):
                db.testcollection.insert ({ 'surfaceStart': w,'surfaceEnd': word,'Relation': relation, "pos": posnum, "neg": negnum })

不幸的是,这段代码有一个奇怪的行为。 似乎无法控制关系并为每个关系插入文档,在 testcollection 中,3 次。 就我的 IF 函数而言,我不明白为什么会这样。

document['rel'] 似乎是一个字符串: "r/instanceOf" 在您发布的所有示例中。字符串上的 find 方法 returns 项目在字符串中的位置,如果未找到则为 -1; -1 在布尔上下文中为真。

无论如何你都不关心字符串的位置,所以你不应该使用 find。使用普通 in:

if 'Synonym' in document['rel']:
    ...

if 'Related' in document['rel'] or 'Derived' in document['rel']: