我想以一种有效的方式在Python中查询Solr mlt术语。我有一个全称列表,例如:
names = ['Bobby Johnson', 'James Bob']
要查询solr中每个人的mlt条件,您必须使用以下url:
'http://localhost:8382/solr/core/mlt?q=name:"Bobby Johnson"&fl=*,score&mlt.fl=concepts&mlt.interestingTerms=details'
'http://localhost:8382/solr/core/mlt?q=name:"James Bob"&fl=*,score&mlt.fl=concepts&mlt.interestingTerms=details'
正如您在上面的示例中看到的,对带有空格的全名的查询在引号中表示。这是有效的,除了它是重复的工作,因为名字列表很大。
如果我试图更有效地做到这一点,通过使用f-string在for循环中查询列表中的每个项目,我得到一个Invalid URL错误(见下文)。我代码:
from urllib.request import urlopen
for name in names:
req = urlopen(f'http://localhost:8382/solr/core/mlt?q=name:"{name}",score&mlt.fl=concepts&mlt.interestingTerms=details')
request_json = json.load(req)
interesting_terms = request_json['interestingTerms']
print(interesting_terms)
#Error message:
InvalidURL: URL can't contain control characters. '/solr/core/mlt?q=name:"Bobby Johnson",score&mlt.fl=concepts&mlt.interestingTerms=details' (found at least ' ')
关于如何处理Python中的多个请求,当查询包含空白时,有什么具体的想法/例子吗?
期望输出值:能够为列表中的每个全名发送请求,并以json格式返回信息。
在生成URL时,在将其发送到urlopen之前必须转义该值:
from urllib.request import urlopen
from urllib.parse import quote_plus
for name in names:
req = urlopen(f'http://localhost:8382/solr/core/mlt?q=name:"{quote_plus(name)}",score&mlt.fl=concepts&mlt.interestingTerms=details')
...