【问题标题】:How to search for a specific word in multiple files如何在多个文件中搜索特定单词
【发布时间】:2022-01-13 17:13:06
【问题描述】:

如何使用 C# 在目录中的多个文件中找到特定单词

下面的代码会在一个单个文件中给我出现,我如何转换它以便它会在所有文件中搜索一个特定的词并给我这个词数?

string text = File.ReadAllText(@"D:\Temp\MyText.txt").ToLower();
int hellos = Regex.Matches(text, @"\bhello\b").Count;

如果我可以使用任何其他方法以更简单的方式完成,请告诉我。

【问题讨论】:

  • 仅供参考:您可以使用不区分大小写的正则表达式查询,而不是将所有文本转换为小写:Regex.Matches(text, @"\bhello\b", RegexOptions.IgnoreCase)

标签: c# file


【解决方案1】:

让我们在 Linq 的帮助下查询目录:

using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

...

int hellos = Directory
  .EnumerateFiles(@"D:\Temp", "*.txt")
  .Select(file => File.ReadAllText(file))
  .Select(text => Regex.Matches(text, @"\bhello\b", RegexOptions.IgnoreCase).Count)
  .Sum();

【讨论】:

    【解决方案2】:

    试试这个:

    private int GetWordCountInFiles(string FolderPath, string SearchWord, string FileExtension)
        {
            int WordCount = 0;
            string[] Files = System.IO.Directory.GetFiles(FolderPath);
    
            for (int i = 0; i < Files.Length; i++)
            {
                string text = System.IO.File.ReadAllText(Files[i]).ToLower();
                WordCount += System.Text.RegularExpressions.Regex.Matches(text, @"\b" + SearchWord + "\b").Count;
            }
            return WordCount;
        }
    

    下面是一个如何使用函数的例子:

    int WordCount = GetWordCountInFiles(@"F:\", "Hello", ".txt");
    

    【讨论】:

    • 不要忘记“一个目录中的所有文件”的要求。也许值得一提的是区分大小写。小注意 C# locat vars 使用 camelCase
    猜你喜欢
    • 2021-04-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    相关资源
    最近更新 更多