簡體   English   中英

如何計算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;
}

它給出了這樣的輸出

這段代碼在字典中返回單詞及其頻率。 我現在需要兩個單詞的版本。 這將計算兩個單詞在字符串中緊隨其后出現的次數。

我應該修改正則表達式嗎? 如果是,該如何修改?

我認為,無需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 (n+1)-th元素和第(n+1)-th元素的元組。 在第四行中,這些元組由它們自己分組(兩個具有相同元素的元組視為相等)。 在最后一步/行中,對每個組的元素進行計數,並將計數及其各自的值存儲在匿名鍵入的變量中。

此邏輯也可以應用於您的RegExp版本。

編輯:要獲得字典,例如您的示例,可以使用ToDictionary擴展方法

var countedCombinations = groupedTuples.ToDictionary(g => g.First(), g => g.Count());

第一個參數是鍵的選擇器方法,第二個參數是值的選擇器方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM