搜索结果的文章内容显示 c# code/Lucene.Net

这里给大家带来一个搜索结果的高亮显示的新方案.

你们以前用Lucene.Net搜索结果显示的时候可能直接用的是 PanGu.HighLight.dll。

效果不是很理想!

为了模拟百度的搜索结果---结果的一个docment单位的文章内容一般分为两段关联内容。如下图:

搜索结果的文章内容显示 c# code/Lucene.Net_第1张图片

不多说,上代码,

using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace searchTset { public class myHighLight { /// <summary>
        /// 高亮html /// </summary>
        /// <param name="body"></param>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public static string getHighLight(string body,string strKey) { string returnStr = ""; string Interval = " ... ";//关联分别

            string bodyToLower = body.ToLower(); strKey = strKey.ToLower(); string startStr="<font color=\"red\">"; string endStr="</font>"; int length=strKey.Length; int bodylength = body.Length; int startlength=startStr.Length; int endlength=endStr.Length; int allLength = startlength + endlength; int FragmentSize = 80;//一个关联段的内容大小

            int infonumber = 2;//相关内容的个数

            int startCorrelationLength = FragmentSize/2; int endCorrelationLength = startCorrelationLength; int startIndex=0; int index=0; if (bodylength < FragmentSize) { index = bodyToLower.IndexOf(strKey, startIndex); if(index>0) { body = body.Insert(index + length, endStr); //先插end避免index实际增加
                   body= body.Insert(index,startStr); startIndex = index + length + allLength; } return body; } int infocount = 0; while(true) { if (infocount >= infonumber) { break; } index = bodyToLower.IndexOf(strKey, startIndex); if(index>0) { body = body.Insert(index + length, endStr); //先插end避免index实际增加
                    body = body.Insert(index, startStr); startIndex = index + length + allLength; bodyToLower = body.ToLower(); int sut = index - startCorrelationLength; int sut1 = bodylength - index; if (sut < 0) { returnStr += body.Substring(0, FragmentSize + allLength) + Interval; } else if (sut1 < endCorrelationLength) { returnStr += body.Substring(bodylength - (FragmentSize + allLength), bodylength + allLength) + Interval; } else { returnStr += body.Substring(index - (startCorrelationLength + startlength), FragmentSize + allLength) + Interval; } infocount++; } else { break; } } return returnStr; } } }

效果如下:

搜索结果的文章内容显示 c# code/Lucene.Net_第2张图片

你可能感兴趣的:(Lucene)