zoukankan      html  css  js  c++  java
  • Lucene4Net以及盘古分词

    l 打开PanGu4Lucene\WebDemo\Bin,将Dictionaries添加到项目根路径(改名为Dict),添加对PanGu.dll(同目录下不要有Pangu.xml,那个默认的配置文件的选项对于分词结果有很多无用信息)、PanGu.Lucene.Analyzer.dll的引用

    l 把上节代码的AnalyzerPanGuAnalyzer代替

    l 运行报错?通用技巧:把Dict目录下的文件“复制到输出目录”设定为“如果较新则复制”。

    对以下引用进行添加:

    使用代码示例:

    Analyzer analyzer = new PanGuAnalyzer();
                //Analyzer analyzer = new StandardAnalyzer();//new后面的类为分词的方法
                TokenStream tokenStream = analyzer.TokenStream("", new System.IO.StringReader(TextBox1.Text));
                Lucene.Net.Analysis.Token token = null;
                while ((token = tokenStream.Next()) != null)
                {
                    //Console.WriteLine(token.TermText());
                    Response.Write(token.TermText()+"<br/>");
                }

    Lucene.Net核心类简介

    l Directory表示索引文件(Lucene.net用来保存用户扔过来的数据的地方)保存的地方,是抽象类,两个子类FSDirectory(文件中)、RAMDirectory (内存中)。使用的时候别和IO里的Directory弄混了。

    l 创建FSDirectory的方法,FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath),new NativeFSLockFactory()), path索引的文件夹路径

    l IndexReader对索引进行读取的类,对IndexWriter进行写的类。

    l IndexReader的静态方法bool IndexExists(Directory directory)判断目录directory是否是一个索引目录。IndexWriterbool IsLocked(Directory directory) 判断目录是否锁定,在对目录写之前会先把目录锁定。两个IndexWriter没法同时写一个索引文件。IndexWriter在进行写操作的时候会自动加锁,close的时候会自动解锁。IndexWriter.Unlock方法手动解锁(比如还没来得及close IndexWriter 程序就崩溃了,可能造成一直被锁定)。

     

     

    创建索引:

    l 构造函数:IndexWriter(Directory dir, Analyzer a, bool create, MaxFieldLength mfl)因为IndexWriter把输入写入索引的时候,Lucene.net是把写入的文件用指定的分词器将文章分词(这样检索的时候才能查的快),然后将词放入索引文件。

    l void AddDocument(Document doc),向索引中添加文档(Insert)。Document类代表要索引的文档(文章),最重要的方法Add(Field field),向文档中添加字段。Document是一片文档,Field是字段(属性)。Document相当于一条记录,Field相当于字段。

    l Field类的构造函数 Field(string name, string value, Field.Store store, Field.Index index, Field.TermVector termVector)

    l  name表示字段名; value表示字段值;

    l store表示是否存储value值,可选值 Field.Store.YES存储, Field.Store.NO不存储, Field.Store.COMPRESS压缩存储;默认只保存分词以后的一堆词,而不保存分词之前的内容,搜索的时候无法根据分词后的东西还原原文,因此如果要显示原文(比如文章正文)则需要设置存储。

    l  index表示如何创建索引,可选值Field.Index. NOT_ANALYZED

    l ,不创建索引,Field.Index. ANALYZED,创建索引;创建索引的字段才可以比较好的检索。是否碎尸万段!是否需要按照这个字段进行“全文检索”。

    l termVector表示如何保存索引词之间的距离。“北京欢迎你们大家”,索引中是如何保存“北京”和“大家”之间“隔多少单词”。方便只检索在一定距离之内的词。

    l 为什么要把帖子的url做为一个Field,因为要在搜索展示的时候先帖子地址取出来构建超链接,所以Field.Store.YES;一般不需要对url进行检索,所以Field.Index.NOT_ANALYZED

    l 案例:对10001100号帖子进行索引。“只要能看懂例子和文档,稍作修改即可实现自己的需求

    1、对数据进行索引

    string indexPath = "c:/temp";
    FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath),new NativeFSLockFactory());
    bool isUpdate = IndexReader.IndexExists(directory);
                if (isUpdate)
                {
                    //如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁
                if (IndexWriter.IsLocked(directory))
                    {
                      IndexWriter.Unlock(directory);
                    }
            }
     IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);
                for (int i = 1000; i < 1100; i++)
                {
                    string txt = File.ReadAllText(@"C:\MxDownload\dnt_3.1.0_sqlserver\upload_files\文章\" + i + ".txt");
                    Document document = new Document();
                    document.Add(new Field("number", i.ToString(), Field.Store.YES, Field.Index. NOT_ANALYZED));
                    document.Add(new Field("body", txt, Field.Store.YES, Field.Index. ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
                    writer.AddDocument(document);
                    Console.WriteLine("索引"+i+"完毕");
                }
                writer.Close();
                directory.Close();//不要忘了Close,否则索引结果搜不到

    搜索:

    l IndexSearcher是进行搜索的类,构造函数传递一个IndexReaderIndexSearchervoid Search(Query query, Filter filter, Collector results)方法用来搜索,Query是查询条件, filter目前传递null, results是检索结果,TopScoreDocCollector.create(1000, true)方法创建一个Collector1000表示最多结果条数,Collector就是一个结果收集器。

    l Query有很多子类,PhraseQuery是一个子类。 PhraseQuery用来进行多个关键词的检索,调用Add方法添加关键词,query.Add(new Term("字段名", 关键词))PhraseQuery. SetSlop(int slop)用来设置关键词之间的最大距离,默认是0,设置了Slop以后哪怕文档中两个关键词之间没有紧挨着也能找到。

    • query.Add(new Term("字段名", 关键词))

    • query.Add(new Term("字段名", 关键词2))

    • 类似于:where 字段名 contains 关键词 and 字段名 contais 关键词2

    l 调用TopScoreDocCollectorGetTotalHits()方法得到搜索结果条数,调用HitsTopDocs TopDocs(int start, int howMany)得到一个范围内的结果(分页),TopDocsscoreDocs字段是结果ScoreDoc数组, ScoreDoc doc字段为Lucene.Net为文档分配的id(为降低内存占用,只先返回文档id),根据这个id调用searcherDoc方法就能拿到Document了(放进去的是Document,取出来的也是Document);调用doc.Get("字段名")可以得到文档指定字段的值,注意只有Store.YES的字段才能得到,因为Store.NO的没有保存全部内容,只保存了分割后的词。

    l 编写检索功能,搜索“网站 志愿者”。练习分词,用户不用空格。如果确定用盘古分词,那么用盘古的Segment类更方便。

    l 检索不出来的可能的原因:路径问题,分词是否正确、盘古分词如果指定忽略大小写,则需要统一按照小写进行搜索

    l Todo:第一个版本应该保存bodytitle,搜索结果形成超链接,不显示正文。

    搜索代码:

    string kw = Console.ReadLine();
    FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
                IndexReader reader = IndexReader.Open(directory,true);
                IndexSearcher searcher = new IndexSearcher(reader);
                PhraseQuery query = new PhraseQuery();
                foreach (string word in kw.Split(' '))//先用空格,让用户去分词,空格分隔的就是词“计算机   专业”
                {
                    query.Add(new Term("body", word));
                }
                query.SetSlop(100);
                 TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
                    searcher.Search(query, null, collector);
             ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;
     for (int i = 0; i < docs.Length; i++)
                    {                    
                        int docId = docs[i].doc;
                        Document doc = searcher.Doc(docId);
                       Console.WriteLine(doc.Get("number"));
                    Console.WriteLine(doc.Get("body"));
                }

    网页采集:

    l 复习WebClient的用法,调用DownloadString方法下载页面。抓取DiscuzNT!的9001000贴。乱码怎么办?乱码的唯一原因“编码不一致”。

    l WebClient抓取到的是页面的源代码,如何得到页面的标题、文字、超链接呢?

    l 用mshtml进行html的解析,IE就是使用mshtml进行网页解析的。添加对Microsoft.mshtml的引用(如果是VS2010,修改这个引用的“嵌入互操作类型”为False。(*“复制本地”设置为True“特定版本”设置为False,这样在没有安装VS的机器中也可以用。)

    •  HTMLDocumentClass doc = new HTMLDocumentClass();

    • doc.designMode = "on"; //不让解析引擎去尝试运行javascript

    • doc.IHTMLDocument2_write(要解析的代码);

    • doc.titledoc.body.innerText,更多用法自己探索。

    • 所有Dom方法都能在mshtml中调用

    搜索结果高亮显示的方法:

    l 高亮显示,只显示包含关键词的部分。参考盘古分词的文档。

    l 从网上、文档找来的代码不用细读每行代码,先把它拿过来运行通过再说。

    l 不用每次改代码都重启,在项目的属性页面的Web中选中“启用编辑并继续(Enable Edit and Continue

    高亮显示的代码:

    private static String highLight(string keyword,String content) 
            {
                PanGu.HighLight.SimpleHTMLFormatter formatter = new PanGu.HighLight.SimpleHTMLFormatter("<font color='red'>", "</font>");
                PanGu.HighLight.Highlighter highlighter = new PanGu.HighLight.Highlighter(formatter, new Segment());
                highlighter.FragmentSize = 500;
                string msg = highlighter.GetBestFragment(keyword,content);
    if (string.IsNullOrEmpty(msg))
                {
                    return content;
                }
                else
                {
                    return msg;
                }
            }
    
    
     String hightlightTitle = highLight(keyword, title);
                        String hightlightBody = HttpUtility.HtmlEncode(body);//防止XSS攻击
                        hightlightBody = highLight(keyword, hightlightBody);
  • 相关阅读:
    Machine learning 第8周编程作业 K-means and PCA
    Machine learning 第7周编程作业 SVM
    Machine learning第6周编程作业
    Machine learning 第5周编程作业
    小M的作物 最小割最大流
    k-近邻算法 python实现
    编辑距离 区间dp
    Machine learning第四周code 编程作业
    MDK5报错missing closing quote
    HDU 5512
  • 原文地址:https://www.cnblogs.com/xuhongfei/p/2939755.html
Copyright © 2011-2022 走看看