谷歌目前使用的关键字,例如site:或者is:在搜索(第二个例子是来自Gmail).我正在尝试开发一个类似的系统,我想知道如何最好地识别和处理这些术语.为简单起见,假设使用了OO语言(Ruby,Python,Java,C#等).
目前,我的计划是为每个关键字分别设置一个类.这些类具有优先级值和三种方法:
isRelevant(String searchPhrase):如果搜索短语与类的过滤器匹配,则返回true.getResults(String searchPhrase):根据搜索短语返回结果列表.reviseSearch(String searchPhrase):返回搜索短语的修改版本.这通常会删除匹配以避免由低优先级实例再次处理,但也可能添加文本或完全清除字符串.然后调用方法将通过这些关键字过滤器,直到搜索短语为空或没有更多过滤器(在后一种情况下,它将恢复其正常的搜索行为).
因此,问题是:这是最有效的方法,还是有更合适的方法?一些细节仍然需要弄清楚,但这是朝着正确方向迈出的一步吗?
foo:(hello world) bar:(-{bad things}) email:something@email.tld another:weird characters +=2{-52!%#^ final:end
/\s+(?=\w+:)/
[
'foo:(hello world)',
'bar:(-{bad things})',
'email:something@email.tld',
'another:weird characters +=2{-52!%#^',
'final:end'
]
Run Code Online (Sandbox Code Playgroud)
\s+ one or more spaces
(?= followed by (positive lookahead)
\w+ one or more word characters
: literal `:' (colon character)
)
Run Code Online (Sandbox Code Playgroud)
遍历数组,将每个元素拆分为:(冒号).左侧key可用于调用函数,右侧value可用作函数参数.这应该会让你在这里做任何你想做的事情.
# Search class
class Search
def initialize(query)
@query = query
end
def foo(input)
"foo has #{input}"
end
def bar(input)
"bar has #{input}"
end
def email(input)
"email has #{input}"
end
def another(input)
"another has #{input}"
end
def final(input)
"final has #{input}"
end
def exec
@query.split(/\s+(?=\w+:)/).each do |e|
method, arg = e.split(/:/)
puts send(method, arg) if respond_to? method
end
end
end
Run Code Online (Sandbox Code Playgroud)
q = "foo:(hello world) bar:(-{bad things}) email:something@email.tld another:weird characters +=2{-52!%#^ final:end";
s = Search.new(q)
s.exec
Run Code Online (Sandbox Code Playgroud)
foo has (hello world)
bar has (-{bad things})
email has something@email.tld
another has weird characters +=2{-52!%#^
final has end
Run Code Online (Sandbox Code Playgroud)