如何将结果(从python)写入mongodb(json)?

2024-05-16 02:02:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在写一份工作清单。对于一个JobID,我想输出它相似的作业(按自定义分数降序排列)。例如,结构应为:

"_id":"abcd","job":1234,"jobList":[{"job":1,"score":0.9},{"job":2,"score":0.8},{"job":3,"score":0.7}]}

这里的JobID是1234,job1、2、3是它的相似作业,按名称得分对列出。 我的python代码是:

def sortSparseMatrix(m, rev=True, only_indices=True):
    f=open("/root/workspace/PythonOutPut/test.json",'wb')
    w=csv.writer(f,dialect='excel')
    col_list = [None] * (m.shape[0])
    j=0
    for i in xrange(m.shape[0]):

        d=m.getrow(i)

        if len(d.indices) != 0:
            s=zip(d.indices, d.data)
            s.sort(key=lambda v:v[1], reverse=True)
            if only_indices:
                col_list[j] =[[element[0],element[1]] for element in s]
                col_list[j]=col_list[j][0:4]

                h1 = u'Job'+":" +str(col_list[j][0][0])+","
                json.dump(h1,f)



                h2=[]
                h3=u'JobList'+":"
                json.dump(h3,f)
                for subrow in col_list[j][1:]:
                   h2.append(u'{Job'+":"+str(subrow[0])+","u'score'+":"+str(subrow[1])+"}")
                json.dump(h2,f)
                del col_list[j][:]
                j=j+1

其中,d包含与JobID有关的未排序的名称得分对:col_list[j][0][0](排序后,与JobID(col_list[j][0][0])最相似的作业(最高得分)是其本身)。d.data是得分,[element[0],element[1]]是名称得分对。我想保留最相似的三份工作。我想先转储h1(显示JobID),然后在h2中输出类似作业的列表。你知道吗

我输入了'mongodbimport--db test\u database--collection TestOfJSON--type csv--file/as above/--fields JobList'。它可以将结果导入mongodb。但是,它只是一个具有多个字段的JobID。但我想要的是JobID只与它相似的Job的name-score对相关联。我该怎么办?谢谢


Tags: in名称jsontruefor作业jobcol