如何使用 C# 在目錄內的多個檔案中找到特定單詞
下面的代碼將在單個檔案中給我出現,我如何轉換它以便它在所有檔案中搜索特定單詞并給我字數?
string text = File.ReadAllText(@"D:\Temp\MyText.txt").ToLower();
int hellos = Regex.Matches(text, @"\bhello\b").Count;
請讓我知道我是否可以使用任何其他方法以更簡單的方式做到這一點。
uj5u.com熱心網友回復:
讓我們在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();
uj5u.com熱心網友回復:
試試這個:
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");
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/413545.html
標籤:
下一篇:ERC20代幣標準初識
