Python中的集合项

Python中的集合项,python,Python,在我的mongoDB数据库中,我有一个如下项目的集合: {u'Keywords': [[u'european', 7], [u'bill', 5], [u'uk', 5], [u'years', 4], [u'brexit', 4]], u'Link': u'http://www.bbc.com/ news/uk-politics-39042876', u'date': datetime.datetime(2017, 2, 21, 22, 47, 7, 463000), u'_id': Obje

在我的mongoDB数据库中,我有一个如下项目的集合:

{u'Keywords': [[u'european', 7], [u'bill', 5], [u'uk', 5], [u'years', 4], [u'brexit', 4]], u'Link': u'http://www.bbc.com/
news/uk-politics-39042876', u'date': datetime.datetime(2017, 2, 21, 22, 47, 7, 463000), u'_id': ObjectId('58acc36b3040a218bc62c6d3')}
.....
这些来自mongo DB查询

   mydb = client['BBCArticles']
    ##mydb.adminCommand({'setParameter': True, 'textSearchEnabled': True})
    my_collection = mydb['Articles']
    print 'Articles containing  higher occurences of the keyword is sorted as follow:'
    for doc in my_collection.find({"Keywords":{"$elemMatch" : {"$elemMatch": {"$in": [keyword.lower()]}}}}):
        print doc
但是,我想按如下方式打印文档:

doc1
Kewords: european,bill, uk
Link:"http://www.bbc.com/"

doc2
....

由于您的集合看起来像一个字典的
列表
,因此应该可以使用
for
-循环对其进行分析。如果您确实只需要url和关键字的一部分,则应该这样做:

# c = your_collection, a list of dictionaries

from urlparse import urlparse

for n in range(len(c)):
    print 'doc{n}'.format(n=n+1)
    for k, v in c[n].iteritems():
        if k == 'Keywords':
            print k+':', ', '.join([str(kw[0]) for kw in v[0:3]])
        if k == 'Link':
            parsed_uri = urlparse( v )
            domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
            print k+':', '"{0}"\n'.format(domain)
印刷品:

doc1
Keywords: european, bill, uk
Link: "http://www.bbc.com/"

对我来说,这似乎是相当武断的要求。为什么不是完整的url,为什么不是所有的关键字?还有
doc1
doc2
来自哪里?它们的格式是否为
docN
,其中
N
只是随着每个项目的增加而增加?为了改进您的问题,您应该描述预期的转换,并展示您迄今为止所做的尝试。更新了我的问题。