0

我想在一个文本文件中同时搜索几个单词。

例如认为我想搜索这 3 个词:Majid,superuser,device

通常我应该一个一个地搜索它们,我不能同时搜索它们。所以我想在一个文本文件中同时搜索这些词。

我想在文本文件中输入这 3 个单词,每行一个单词。我们将其命名为 SearchText。现在我有一个目标文本,我想在其中搜索这些词。我们将其命名为 TargetText。

我想告诉一个应用程序或类似的东西从 SearchText 中获取单词并在 TargetText 中找到它们并突出显示它们或给我查找结果。

我希望我很清楚。那么有人可以帮帮我吗?

4

1 回答 1

1

你很清楚。我认为最好的选择是正则表达式。
试试这个:

Option Explicit
Dim oFso        : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim srcPath     : SrcPath = oFso.GetParentFolderName(WScript.ScriptFullName)
Dim sWordList   : sWordList = ofso.OpenTextFile(oFso.BuildPath(srcPath, "search.txt")).ReadAll()
Dim sTargFile   : sTargFile = ofso.OpenTextFile(oFso.BuildPath(srcPath, "target.txt")).ReadAll()
Dim strWords    : strWords = Join(Split(sWordList, vbCrLf), "|")
Dim oReg        : Set oReg = New RegExp
Dim oDict       : Set oDict = CreateObject("Scripting.Dictionary") 'for found words
oDict.CompareMode = vbTextCompare 'case insensitive

With oReg
    .Global = True
    .IgnoreCase = True
    .Pattern = "("& strWords &")" ' (word1|word2|word3|etc..)
    'if the words contain some special chars for regex, you may need to escape with \ char
    'see the information below: http://goo.gl/cqGVp
    Dim collFND : Set collFND = oReg.Execute(sTargFile)
    Dim Fnd
    'WScript.Echo String(50, "-")
    For Each Fnd In collFND
        With Fnd
            'WScript.Echo "Word : "& .Value, ", Position: ("& .FirstIndex &","& .Length &")"
            oDict(.Value) = ""
        End With
    Next
    Set collFND = Nothing
    'WScript.Echo String(50, "-"), vbCrLf, "Higlighted Output:", oReg.Replace(sTargFile, "[$1]")
    ofso.CreateTextFile(oFso.BuildPath(srcPath, "foundwords.txt"),True).Write(Join(oDict.Keys, vbCrLf)) 'found words saved
End With
于 2011-09-11T13:50:45.673 回答