一、建立网页库和偏移文件
为文本搜索引擎建立网页库,首先要把所有的网页(这里是文章)格式化,并保存到指定的格式中。如以下格式:
|
| <doc>
| <docid>...</docid>
| <url>...</url>
| <title>...</title>
| <content>...</content>
| </doc>
| <doc>
| ...
| </doc>
| ...
其中<doc>……</doc>保存着一篇文章;<docid>...</docid> 保存文档id;<url>...</url>保存文本路径;<content>...</content> 保存文章内容。
如何生成这样的格式呢?对每一篇文章使用以下方法:
首先从文章中提取标题 title;以及获得文章的路径,然后用字符串拼接,拼接成上述格式。
std::ofstream ofs("pages.lib",std::ios::out);//打开网页库
std::ofstream out("offset.lib",std::ios::out); //打开偏移文件
string txt = "<doc><docid>" + docid + "</docid>" + "<url>" + url + ... + "</doc>"; ofs << txt; //写到文件流 int offset = ofs.tellg();// offset 获得当前指针的位置 ,tellg()和tellp()是C++文件流操作中获得流指针的函数 int length = txt.size();//length out<<docid<<" "<<offset<<""<<length<<endl;//将这片文章的起始位置和偏移量写到偏移文件中,便于后面从网页库中读出一篇网页
循环对所有文章执行上面的操作,就得到一个网页库和一个偏移文件。
二、解析网页
根据偏移文件,从网页库中读出一篇网页,接着对网页库中的docid,title,url进行解析。
以下是解析器的代码:
1 #ifndef _XMLPARSER_HPP 2 #define _XMLPARSER_HPP 3 #include <stdio.h> 4 #include <utility> 5 #include <string> 6 #include <stdlib.h> 7 using namespace std; 8 class XMLParser 9 { 10 public: 11 XMLParser(string & page) 12 :page_(page) 13 {} 14 string parser(string tag) 15 { 16 string ltag,rtag; 17 ltag = "<"+tag+">"; //拼接左标签 18 rtag = "</"+tag+">"; //拼接右标签 19 string str; 20 //pair<string,string> pr; 21 string::size_type bpos; 22 string::size_type epos; 23 string::size_type len; 24 //确定字符串范围 25 bpos = page_.find(ltag);//查找作标签下标 26 epos = page_.find(rtag);//查找右标签下标 27 bpos+=ltag.size(); 28 len = epos - bpos; //计算标签包含内容长度 29 if(bpos==page_.npos||epos==page_.npos) 30 { 31 printf("No such tag: %s ",tag.c_str()); 32 exit(-1); 33 } 34 if(bpos==epos) 35 { 36 printf("标签内容不存在 "); 37 exit(-1); 38 } 39 40 string content = page_.substr(bpos+1,len-2);//截取标签包含内容 41 #if 0 42 if(content[content.size()-1]==' ') 43 content[content.size()-1]=='