如何在查询中按术语从列表中查找文档(如果列表文档中存在至少一个查询术语)

时间:2016-06-18 09:33:37

标签: python

我的查询列表和此类文档列表

queries = ['drug dosage form development Society', 'new drugs through activity evaluation of some medicinally used plants', ' Evaluation of drugs available on market for their quality, effectiveness']
docs = ['A Comparison of Urinalysis Technologies for Drugs Testing in Criminal Justice', 'development society and health care', 'buying drugs on the market without prescription may results in death', 'plants and their contribution in pharmacology', 'health care in developing countries']

如果查询和文档中至少存在一个相似的单词,我想将文档打印为相关文档。我已根据python: finding substring within a list帖子的一个答案尝试了此代码。但它不起作用。

query = [subquery for subquery in queries]
for i in query:
    sub = i
    for doc in docs:
        if str(i) in docs:
            print docs

任何帮助都很明显

2 个答案:

答案 0 :(得分:0)

您的代码(for i in query:)正在搜索句子而非单词。 要搜索单词,首先必须将查询语句拆分为单词。

for q in queries:
    for word in q.strip().split(" "):
        print word

完整代码:

for q in queries:
    for word in q.strip().split(" "):
        for doc in docs:
            if word in doc:
                print doc

注意:上面的代码也会在doc

中搜索in, for, of, on

答案 1 :(得分:0)

这样做的有效方法是构建倒置索引。我在下面实现的是一个脏的倒排索引。

words = {}
for index, doc in enumerate(docs):
    for word in doc.split(" "): 
        if not word or word==" ":
            pass
        elif not word in words: words[word]=[index]
        elif index not in words[word]: words[word].append(index)

for query in queries: 
    matches = []
    map(lambda x: matches.extend(words[x]), filter(lambda x: x in query, words))
    print list(set(matches))

在理想的世界中,您的代码还包括

  • 停用词 - 不应编入索引的词,例如文档中的“for”或“the”。
  • 词干 - 将单词映射到其词干,允许进行替代语法搜索。例如,运行 - >跑,跑 - > run,runner - >跑。因此,使用任何术语都会带来包含单词run的文档及其所有形式。
  • 同义词 - 查找Wordnet或类似数据库中的同义词。例如。车辆也会提出包含“汽车”一词的文件。
  • 相关性排名 - 检索到的文档可以根据搜索项的频率相对于文档中的单词总数进行排名。

以上所有内容都可以作为附加模块添加到您根据需要创建的索引和搜索引擎上。

相关问题