gpt4 book ai didi

Ruby:在倒排索引中搜索部分匹配

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:01 24 4
gpt4 key购买 nike

我需要在倒排索引中搜索部分匹配,以下代码适用于完全匹配但不适用于部分匹配。从 http://rosettacode.org/wiki/Inverted_Index 的示例中修改了此内容(不再适用于 Ruby1.9.3)

请问如何最有效地做到这一点?请不要建议使用 Lucene、Sphinx 等,除非你知道一个轻量级、简单和纯 Ruby 解决方案,想自己做。

@data = {"contents"=>["1.txt", "2.txt"], "of"=>["1.txt", "2.txt"], "file"=>["1.txt", "2.txt"], "one"=>["1.txt"], "two"=>["2.txt"]}

def search words
result = []
words.each do |word|
result << @data[word] if @data[word] #should do a partial match
end
result
end

p search ['of'] #=> [["1.txt", "2.txt"]]
p search ['one'] #=> [["1.txt"]]
p search ['on'] #=> [] <<should become [["1.txt"]]

最佳答案

定义搜索如下:

def search words
words.map do |word|
matches = @data.keys.select {|key| key.include?(word)}
matches.map {|match| @data[match] }
end
end

p search ['of'] #=> [[["1.txt", "2.txt"]]]
p search ['one'] #=> [[["1.txt"]]]
p search ['on'] #=> [[["1.txt", "2.txt"], ["1.txt"]]] - note that "contents" contains "on"

关于Ruby:在倒排索引中搜索部分匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10951892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com