我很接近,但我的程序仍然无法正常工作。我试图计算一组单词在文本文件中出现的次数,列出这些单词及其单个计数,然后给出所有找到的匹配单词的总和。
如果有 3 个“lorem”实例,2 个“ipsum”实例,那么总数应该是 5。我的示例文本文件只是在文本文件中重复几次的“Lorem ipsum”段落。
我的问题是到目前为止我的这段代码只计算每个单词的第一次出现,即使每个单词在整个文本文件中重复多次。
我正在使用一个名为“GroupDocs.Parser”的“付费”解析器,它是通过 NuGet 包管理器添加的。如果可能的话,我宁愿不使用付费版本。
在 C# 中有没有更简单的方法来做到这一点?
这是我想要的结果的屏幕截图。
这是我到目前为止的完整代码。
using GroupDocs.Parser;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
using (Parser parser = new Parser(@"E:\testdata\loremIpsum.txt"))
{
// Extract a text into the reader
using (TextReader reader = parser.GetText())
{
// Define the search terms.
string[] wordsToMatch = { "Lorem", "ipsum", "amet" };
Dictionary<string, int> stats = new Dictionary<string, int>();
string text = reader.ReadToEnd();
char[] chars = { ' ', '.', ',', ';', ':', '?', '\n', '\r' };
// split words
string[] words = text.Split(chars);
int minWordLength = 2;// to count words having more than 2 characters
// iterate over the word collection to count occurrences
foreach (string word in wordsToMatch)
{
string w = word.Trim().ToLower();
if (w.Length > minWordLength)
{
if (!stats.ContainsKey(w))
{
// add new word to collection
stats.Add(w, 1);
}
else
{
// update word occurrence count
stats[w] += 1;
}
}
}
// order the collection by word count
var orderedStats = stats.OrderByDescending(x => x.Value);
// print occurrence of each word
foreach (var pair in orderedStats)
{
Console.WriteLine("Total occurrences of {0}: {1}", pair.Key, pair.Value);
}
// print total word count
Console.WriteLine("Total word count: {0}", stats.Count);
Console.ReadKey();
}
}
}
}
}
关于我做错了什么有什么建议吗?
提前致谢。