【问题标题】:Search a file based on a text file's words根据文本文件的单词搜索文件
【发布时间】:2011-11-14 17:32:23
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

  • 还有,呃……我们在说什么语言?请将其添加为标签。

标签: search vbscript words


【解决方案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

【讨论】:

  • 嗨,Kul-Tigin,再次感谢您的回复,如何告诉这个脚本将找到的单词保存在文本文件中?还有什么方法可以跳过消息吗?
  • 查看代码中有关特殊字符的 cmets。您应该转义特殊字符。
  • 页面确实没有加载:(你能告诉我如何在我的话中使用“\”字符并找到安全的地方吗?
  • 我可以 :) 像这样 \ -> \\ , $ -> \$
  • Kul-Tigin 你真的很棒 :)) 最后一个问题,认为我的搜索词是 Kul,现在在第一行的目标文本中有一个包含 Kul 的句子。我想突出显示整个句子并将其保存在输出文件中,可以吗?
猜你喜欢
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多