如何计算 C# 中字符串中两个单词的出现次数?
How can I count occurences of two words following each other in a string in C#?
我用这样的正则表达式做了一个单词版本:
public Dictionary<string, int> MakeOneWordDictionary(string content)
{
Dictionary<string, int> words = new Dictionary<string, int>();
// Regex checking word match
var wordPattern = new Regex(@"\w+");
// Refactor text and clear it from punctuation marks
content = RemoveSigns(content);
foreach (Match match in wordPattern.Matches(content))
{
int currentCount = 0;
words.TryGetValue(match.Value, out currentCount);
currentCount++;
words[match.Value] = currentCount;
}
return words;
}
这段代码 returns 个单词及其在字典中的出现频率。我现在需要这个的两个单词版本。这将计算字符串中两个单词的出现次数。
我应该修改正则表达式吗?如果是我该如何修改?
我认为这可以在没有 RegExp 的情况下以更自我解释的方式编写。
string input = "a a b test a a";
string[] words = input.Split(' ');
var combinations = from index in Enumerable.Range(0, words.Length-1)
select new Tuple<string,string>(words[index], words[index+1]);
var groupedTuples = combinations.GroupBy(t => t);
var countedCombinations = groupedTuples.Select(g => new { Value = g.First(), Count = g.Count()});
前两行定义输入并用空格分隔,即将其分隔成单个单词。第三行遍历从第一个到 (N-1)th
元素的单词数组(其中 N
是单词的数量)并构建一个 n-th
和 [=15= 的元组] 元素。
在第四行中,这些元组被自己分组(两个具有相同元素的元组被认为是相等的)。在最后 step/line 中,对每个组的元素进行计数,并将计数与它们各自的值一起存储在匿名类型的变量中。
此逻辑也可以应用于您的 RegExp 版本。
编辑:
要获取字典,就像在您的示例中一样,您可以使用 ToDictionary
扩展方法
var countedCombinations = groupedTuples.ToDictionary(g => g.First(), g => g.Count());
第一个参数是键的选择器方法,第二个参数是值的选择器方法。
我用这样的正则表达式做了一个单词版本:
public Dictionary<string, int> MakeOneWordDictionary(string content)
{
Dictionary<string, int> words = new Dictionary<string, int>();
// Regex checking word match
var wordPattern = new Regex(@"\w+");
// Refactor text and clear it from punctuation marks
content = RemoveSigns(content);
foreach (Match match in wordPattern.Matches(content))
{
int currentCount = 0;
words.TryGetValue(match.Value, out currentCount);
currentCount++;
words[match.Value] = currentCount;
}
return words;
}
这段代码 returns 个单词及其在字典中的出现频率。我现在需要这个的两个单词版本。这将计算字符串中两个单词的出现次数。
我应该修改正则表达式吗?如果是我该如何修改?
我认为这可以在没有 RegExp 的情况下以更自我解释的方式编写。
string input = "a a b test a a";
string[] words = input.Split(' ');
var combinations = from index in Enumerable.Range(0, words.Length-1)
select new Tuple<string,string>(words[index], words[index+1]);
var groupedTuples = combinations.GroupBy(t => t);
var countedCombinations = groupedTuples.Select(g => new { Value = g.First(), Count = g.Count()});
前两行定义输入并用空格分隔,即将其分隔成单个单词。第三行遍历从第一个到 (N-1)th
元素的单词数组(其中 N
是单词的数量)并构建一个 n-th
和 [=15= 的元组] 元素。
在第四行中,这些元组被自己分组(两个具有相同元素的元组被认为是相等的)。在最后 step/line 中,对每个组的元素进行计数,并将计数与它们各自的值一起存储在匿名类型的变量中。
此逻辑也可以应用于您的 RegExp 版本。
编辑:
要获取字典,就像在您的示例中一样,您可以使用 ToDictionary
扩展方法
var countedCombinations = groupedTuples.ToDictionary(g => g.First(), g => g.Count());
第一个参数是键的选择器方法,第二个参数是值的选择器方法。