網頁爬蟲WebCrawler(2)-Utilities

來源:互聯網
上載者:User

標籤:爬蟲   類   作業系統相關   

在網頁爬蟲的實現過程中還涉及了一些基本的功能函數,例如擷取系統的目前時間函數,進程休眠和字串替換函數等。

我們將這些多次調用的與過程無關的函數寫成一個類Utilities。

Code:

/////Utilities.h//*************************//與作業系統相關的函數//*************************#ifndef Utilities_H#define Utilities_H#if defined(WIN32)    #include <Windows.h>#else    #include <sys/utime.h>#endif#include <stdio.h>#include <time.h>#include <string>#include <iostream>#include <sstream>#include <fstream>class Utilities{public:static void GetSystemTime(std::string& sdateStr,std::string& stimeStr);static void StringSearchAndReplace(std::string& sourceStr,std::string toReplace,std::string withThisStr);static bool Sleep(long lTimeMsecs);static void find_and_replace(std::string &source,const std::string find,std::string replace);static std::string replaceAll(const std::string& s,const std::string& f,const std::string& r);};#endif


 

//////Utilities.cpp#include "Utilities.h"void Utilities::GetSystemTime(std::string& sdateStr,std::string& stimeStr){char dateStr[9];char timeStr[9];sdateStr=_strdate(dateStr);stimeStr=_strtime(timeStr);}void Utilities::StringSearchAndReplace(std::string& sourceStr,std::string toReplace,std::string withThisStr){std::string::size_type idx=0;while(true){idx=sourceStr.find(toReplace,idx);if(idx==std::string::npos)break;sourceStr.replace(idx,toReplace.size(),withThisStr);idx+=withThisStr.length();}}bool Utilities::Sleep(long lTimeMsecs){#if defined(WIN32)::Sleep(lTimeMsecs);return (true);#elsetimeval tv;tv.tv_sec=lTimeMsecs/1000;tv.tv_usec=(lTimeMsecs%1000)*1000;if(::select(0,0,0,0,&tv)==-1)return (false);elsereturn (true);#endif}void Utilities::find_and_replace(std::string& source,const std::string find, std::string replace){size_t j;for(;(j=source.find(find))!=std::string::npos;)source.replace(j,find.length(),replace);}std::string Utilities::replaceAll(const std::string& s,const std::string& f,const std::string& r){if(s.empty()|| f.empty()|| f==r ||s.find(f)==std::string::npos)return s;std::ostringstream  build_it;size_t i=0;for(size_t pos;(pos=s.find(f,i))!=std::string::npos;){build_it.write(&s[i],pos-i);build_it<<r;i=pos+f.size();}if(i!=s.size())build_it.write(&s[i],s.size()-i);return build_it.str();}


 

網頁爬蟲WebCrawler(2)-Utilities

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.