Python point:adict.has_key(k)在python2.X中已经过时,在python3.X中消失了。k in adict因为从python2.2开始就有了表达式;请改用它。它会更快(没有方法调用)。在
一个任何语言的实用点:在较短的词典上进行迭代。在
综合结果:if len(doca_dic) < len(docb_dict):
short_dict, long_dict = doca_dic, docb_dic
else:
short_dict, long_dict = docb_dic, doca_dic
similarity = 0
for x in short_dict:
if x in long_dict:
#calculate the similarity by summing the products of the tf-idf_norm
similarity += short_dict[x] * long_dict[x]
如果您不需要这两个字典来处理其他任何事情,那么您可以只创建A字典并在B查询中弹出B(key,value)元组进行迭代。在docb = cursor2.fetchall()之后,将以下所有代码替换为:
^{pr2}$
以上代码的另一种选择:这是在做更多的工作,但它用C而不是Python进行更多的迭代,而且可能更快。在similarity = sum(
doca_dic[k] * docb_dic[k]
for k in set(doca_dic) & set(docb_dic)
)
Python代码的最终版本# Doc A
cursor1.execute("SELECT token, tfidf_norm FROM index WHERE doc_id = %s", (docid[i][0]))
doca = cursor1.fetchall()
# Doc B
cursor2.execute("SELECT token, tfidf_norm FROM index WHERE doc_id = %s", (docid[j][0]))
docb = cursor2.fetchall()
if len(doca) < len(docb):
short_doc, long_doc = doca, docb
else:
short_doc, long_doc = docb, doca
long_dict = dict(long_doc) # yes, it should be that simple
similarity = 0
for key, value in short_doc:
if key in long_dict:
similarity += long_dict[key] * value
另一个实际的问题是:你没有说哪一部分速度慢。。。做口述还是做选择?在脚本中加入一些time.time()的调用。在
考虑将所有的工作推送到数据库中。下面的示例使用硬连接的SQLite查询,但原理是相同的。在C:\junk\so>sqlite3
SQLite version 3.6.14
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table atable(docid text, token text, score float,
primary key (docid, token));
sqlite> insert into atable values('a', 'apple', 12.2);
sqlite> insert into atable values('a', 'word', 29.67);
sqlite> insert into atable values('a', 'zulu', 78.56);
sqlite> insert into atable values('b', 'apple', 11.0);
sqlite> insert into atable values('b', 'word', 33.21);
sqlite> insert into atable values('b', 'zealot', 11.56);
sqlite> select sum(A.score * B.score) from atable A, atable B
where A.token = B.token and A.docid = 'a' and B.docid = 'b';
1119.5407
sqlite>
而且值得检查的是,数据库表是否被适当地索引(例如,token上的一个)。。。没有可用的索引是使SQL查询运行非常慢的一个好方法。在
说明:在token上建立索引可能会使现有的查询或“在数据库中做所有工作”查询或两者都运行得更快,这取决于数据库软件中查询优化程序的突发奇想和月球的相位。如果没有可用的索引,数据库将读取表中的所有行。在
创建索引:create index atable_token_idx on atable(token);
删除索引:drop index atable_token_idx;
(但请参阅文档以了解您的数据库)