萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 實作智慧分詞搜尋引擎

核心概念:自動分組關鍵字

使用者輸入「中國人民」,系統自動拆解為「中國」、「人民」等雙字組合,並以 OR 條件查詢,模擬 3721 風格智慧搜尋。

資料庫準備

建立 db_sample.mdb,資料表 T_Sample:

  • ID (Autonumber)
  • U_Name (Text)
  • U_Info (Memo)

搜尋頁面 Search.asp

<form name="frm_Search" method="get" action="Search.asp">
請輸入關鍵字:<input type="text" name="key" size="10">
<input type="submit" value="搜尋">
</form>

資料庫連線

<%
Dim strProvider, CNN
strProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("data/db_Sample.mdb")
Set CNN = Server.CreateObject("ADODB.Connection")
CNN.Open strProvider
%>

智慧分詞核心函數 AutoKey

<%
Function AutoKey(strKey)
    Const lngSubKey = 2 ' 子字串長度
    Dim lngLenKey, strNew1, strNew2, i, strSubKey

    ' 防注入:過濾危險字元
    If InStr(strKey, "=") Or InStr(strKey, "`") Or InStr(strKey, "'") Or InStr(strKey, " ") Or _
       InStr(strKey, Chr(34)) Or InStr(strKey, ",") Or InStr(strKey, "<") Or InStr(strKey, ">") Then
        Response.Redirect "error.htm"
    End If

    lngLenKey = Len(strKey)
    Select Case lngLenKey
        Case 0: Response.Redirect "error.htm"
        Case 1: strNew1 = "" : strNew2 = ""
        Case Else
            For i = 1 To lngLenKey - (lngSubKey - 1)
                strSubKey = Mid(strKey, i, lngSubKey)
                strNew1 = strNew1 & " OR U_Name LIKE '%" & strSubKey & "%'"
                strNew2 = strNew2 & " OR U_Info LIKE '%" & strSubKey & "%'"
            Next
    End Select

    ' 組合完整 SQL:原關鍵字 + 所有雙字組合
    AutoKey = "SELECT * FROM T_Sample WHERE U_Name LIKE '%" & strKey & "%' OR U_Info LIKE '%" & strKey & "%'" & strNew1 & strNew2
End Function
%>

查詢與顯示邏輯

<%
Dim S_Key, SQL, RST
S_Key = Request("key")
If S_Key = "" Then
    Response.Write "<font color=red>請輸入關鍵字</font>"
Else
    SQL = AutoKey(S_Key)
    Set RST = CNN.Execute(SQL)
    If RST.EOF And RST.BOF Then
        Response.Write "<font color=red>未找到任何結果!</font>"
    Else
        Response.Write "搜尋關鍵字:" & S_Key & ",共找到 " & RST.RecordCount & " 筆:<p>"
        While Not RST.EOF
            Response.Write "<font size=2><a href='info.asp?ID=" & RST("ID") & "' target='_blank'>" & RST("U_Name") & "</a></font>"
            Response.Write "<font size=1>" & Left(RST("U_Info"), 150) & "</font><p>"
            RST.MoveNext
        Wend
        RST.Close
    End If
    Set RST = Nothing
End If
CNN.Close : Set CNN = Nothing
%>

為何子字串長度設為 2?

  • 長度 1:失去分組意義,退化為單字搜尋,雜訊極大。
  • 長度 ≥3:易遺漏常用雙字詞(如「中國」、「人民」、「網站」)。
  • 長度 2:平衡精確度與覆蓋率,適合中文語料特性。

擴充建議

  1. 引入斷詞詞典(如 Jieba.NET 移植版)提升分詞準確度。
  2. 加入全文檢索引擎(SQL Server Full-Text Search、Lucene.NET)應對大數據量。
  3. 記錄搜尋熱門詞,提供自動完成與相關推薦。
copyright © 萬盛學電腦網 all rights reserved