分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
#001 // Autocomplete provider forsearches and suggestions from a search engine.
#002 //
#003 // After construction, theautocomplete controller repeatedly calls Start()
#004 // with some user input,each time expecting to receive a small set of the best
#005 // matches (eithersynchronously or asynchronously).
#006 //
#007 // Initially the providercreates a match that searches for the current input
#008 // text. It also starts a task to query the Suggestservers. When that data
#009 // comes back, the providercreates and returns matches for the best
#010 // suggestions.
SearchProvider类是继承AutocompleteProvider和URLFetcher类,AutocompleteProvider提供一个自动完成的结果,URLFetcher主要提供从URL获取数据和状态。
#011 class SearchProvider :public AutocompleteProvider,
#012 public URLFetcher::Delegate {
#013 public:
#014 SearchProvider(ACProviderListener*listener, Profile* profile)
#015 :AutocompleteProvider(listener, profile, "Search"),
#016 last_default_provider_(NULL),
#017 fetcher_(NULL),
#018 history_request_pending_(false),
#019 have_history_results_(false),
#020 suggest_results_pending_(false),
#021 have_suggest_results_(false) {
#022 }
#023
开始获取。
#024 // AutocompleteProvider
#025 virtual void Start(constAutocompleteInput& input,
#026 boolminimal_changes,
#027 boolsynchronous_only);
停止查找。
#028 virtual void Stop();
#029
当获取到数据回来时响应。
#030 // URLFetcher::Delegate
#031 virtual voidOnURLFetchComplete(const URLFetcher* source,
#032 const GURL& url,
#033 const URLRequestStatus& status,
#034 int response_code,
#035 const ResponseCookies& cookies,
#036 const std::string&data);
#037
#038 private:
#039 struct NavigationResult {
#040 NavigationResult(conststd::wstring& url, const std::wstring& site_name)
#041 : url(url),
#042 site_name(site_name) {
#043 }
#044
#045 // The URL.
#046 std::wstring url;
#047
#048 // Name for the site.
#049 std::wstring site_name;
#050 };
#051
保存返回的结果。
#052 typedefstd::vector<std::wstring> SuggestResults;
#053 typedefstd::vector<NavigationResult> NavigationResults;
#054 typedefstd::vector<history::KeywordSearchTermVisit> HistoryResults;
#055 typedefstd::map<std::wstring, AutocompleteMatch> MatchMap;
#056
运行获取搜索引擎数据。
#057 // Called when timer_expires.
#058 void Run();
#059
#060 // Determines whether anasynchronous subcomponent query should run for the
#061 // current input. If so, starts it if necessary; otherwisestops it.
#062 // NOTE: These functionsdo not update |done_|. Callers must doso.
#063 voidStartOrStopHistoryQuery(bool minimal_changes, bool synchronous_only);
#064 voidStartOrStopSuggestQuery(bool minimal_changes, bool synchronous_only);
#065
#066 // Functions to stop theseparate asynchronous subcomponents.
#067 // NOTE: These functionsdo not update |done_|. Callers must doso.
#068 void StopHistory();
#069 void StopSuggest();
#070
#071 // Called back by thehistory system to return searches that begin with the
#072 // input text.
#073 voidOnGotMostRecentKeywordSearchTerms(
#074 CancelableRequestProvider::Handle handle,
#075 HistoryResults*results);
#076
#077 // Parses the results fromthe Suggest server and stores up to kMaxMatches of
#078 // them inserver_results_. Returns whether parsingsucceeded.
#079 boolParseSuggestResults(Value* root_val);
#080
#081 // Converts the parsedserver results in server_results_ to a set of
#082 // AutocompleteMatches andadds them to |matches_|. This also sets|done_|
#083 // correctly.
#084 voidConvertResultsToAutocompleteMatches();
#085
#086 // Determines therelevance for a particular match. We usedifferent scoring
#087 // algorithms for thedifferent types of matches.
#088 int CalculateRelevanceForWhatYouTyped()const;
#089 // |time| is the time atwhich this query was last seen.
#090 intCalculateRelevanceForHistory(const Time& time) const;
#091 // |suggestion_value| iswhich suggestion this is in the list returned from
#092 // the server; the bestsuggestion is suggestion number 0.
#093 intCalculateRelevanceForSuggestion(size_t suggestion_value) const;
#094 // |suggestion_value| issame as above.
#095 intCalculateRelevanceForNavigation(size_t suggestion_value) const;
#096
#097 // Creates anAutocompleteMatch for "Search <engine> for |query_string|" with
#098 // the suppliedrelevance. Adds this match to |map|; ifsuch a match already
#099 // exists, whichever onehas lower relevance is eliminated.
#100 void AddMatchToMap(conststd::wstring& query_string,
#101 intrelevance,
#102 intaccepted_suggestion,
#103 MatchMap* map);
#104 // Returns anAutocompleteMatch for a navigational suggestion.
#105 AutocompleteMatchNavigationToMatch(const NavigationResult& query_string,
#106 intrelevance);
#107
#108 // Trims "http:"and up to two subsequent slashes from |url|. Returns the
#109 // number of charactersthat were trimmed.
#110 // TODO(kochi): this is duplicate fromhistory_autocomplete
#111 static size_tTrimHttpPrefix(std::wstring* url);
#112
#113 // Don't send any queriesto the server until some time has elapsed after
#114 // the last keypress, toavoid flooding the server with requests we are
#115 // likely to end upthrowing away anyway.
#116 static const intkQueryDelayMs;
#117
#118 // The user's input.
#119 AutocompleteInput input_;
#120
#121 TemplateURLdefault_provider_; // Cached across thelife of a query so we
#122 // behave consistently even if the user
#123 // changes their default while the query is
#124 // running.
#125 const TemplateURL*last_default_provider_;
#126 // TODO(pkasting): http://b/1162970 We
#127 // shouldn't need this.
#128
#129 // An object we can use tocancel history requests.
#130 CancelableRequestConsumerhistory_request_consumer_;
#131
#132 // Searches in the user'shistory that begin with the input text.
#133 HistoryResultshistory_results_;
#134
#135 // Whether history_results_is valid (so we can tell invalid apart from
#136 // empty).
#137 boolhave_history_results_;
#138
#139 // Whether we are waitingfor a history request to finish.
#140 boolhistory_request_pending_;
#141
#142 // True if we're expectingsuggest results that haven't yet arrived. This
#143 // could be because either|timer_| or |fetcher| is still running (see below).
#144 boolsuggest_results_pending_;
#145
#146 // A timer to start aquery to the suggest server after the user has stopped
#147 // typing for long enough.
#148 base::OneShotTimer<SearchProvider> timer_;
#149
#150 // The fetcher thatretrieves suggest results from the server.
#151 scoped_ptr<URLFetcher> fetcher_;
#152
#153 // Suggestions returned bythe Suggest server for the input text.
#154 SuggestResultssuggest_results_;
#155
#156 // Navigationalsuggestions returned by the server.
#157 NavigationResultsnavigation_results_;
#158
#159 // Whether suggest_results_is valid.
#160 boolhave_suggest_results_;
#161
#162 DISALLOW_EVIL_CONSTRUCTORS(SearchProvider);
#163 };
#164
在这个类里先调用函数SearchProvider::Start来获取缺省的搜索引擎,然后停止以前的搜索,接着SearchProvider::Run()函数里使用URLFetcher获取数据回来,它的代码如下:
#001 void SearchProvider::Run(){
#002 // Start a new requestwith the current input.
#003 DCHECK(!done_);
获取搜索的URL。
#004 const TemplateURLRef*const suggestions_url =
#005 default_provider_.suggestions_url();
建议代替的字符。
#006 DCHECK(suggestions_url->SupportsReplacement());
开始新的搜索。
#007 fetcher_.reset(newURLFetcher(GURL(suggestions_url->ReplaceSearchTerms(
#008 default_provider_,input_.text(),
#009 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE, std::wstring())),
#010 URLFetcher::GET,this));
#011 fetcher_->set_request_context(profile_->GetRequestContext());
#012 fetcher_->Start();
#013 }
当前上面的搜索完成时,就会通知SearchProvider::OnURLFetchComplete函数来分析返回的结果,最后调用SearchProvider::ConvertResultsToAutocompleteMatches()函数来把结果转换自动完成的列表项。
通过上面的分析,就了解通过GOOGLE搜索引擎自动完成功能的实现。
给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/2e19ffb3303a490d20ea5d00dd397156.gif)