如何显示所有的错字

本文关键字:何显示 显示 | 更新日期: 2023-09-27 18:02:34

我在richTextBox1中有一些文本。

  1. 我必须按频率对单词进行排序,并在richTextBox2中显示它们。这似乎行得通。

  2. 必须找到所有错误的单词并显示在richTextBox4中。我在用魔咒。显然我漏掉了什么。

  3. 几乎所有的单词都显示在richTextBox4中,而不仅仅是错误的。
代码:

foreach (Match match in wordPattern.Matches(str))
{
    if (!words.ContainsKey(match.Value))
        words.Add(match.Value, 1);
    else
        words[match.Value]++;
}
string[] words2 = new string[words.Keys.Count];
words.Keys.CopyTo(words2, 0);
int[] freqs = new int[words.Values.Count];
words.Values.CopyTo(freqs, 0);
Array.Sort(freqs, words2);
Array.Reverse(freqs);
Array.Reverse(words2);
Dictionary<string, int> dictByFreq = new Dictionary<string, int>();
for (int i = 0; i < freqs.Length; i++)
{
    dictByFreq.Add(words2[i], freqs[i]);
}
Hunspell hunspell = new Hunspell("en_US.aff", "en_US.dic");
StringBuilder resultSb = new StringBuilder(dictByFreq.Count); 
foreach (KeyValuePair<string, int> entry in dictByFreq)
{
    resultSb.AppendLine(string.Format("{0} [{1}]", entry.Key, entry.Value));
    richTextBox2.Text = resultSb.ToString();
    bool correct = hunspell.Spell(entry.Key);
    if (correct == false)                
    {
        richTextBox4.Text = resultSb.ToString();
    }    
}

如何显示所有的错字

除了上面的答案(这应该工作,如果你的魔咒。拼写方法工作正确),我有一些建议,以缩短你的代码。您正在向字典中添加Matches,并计算每个match的出现次数。然后,您似乎按照频率降序对它们进行排序(因此,最高的出现匹配将在结果中具有索引0)。这里有一些代码片段,可以使你的函数更短:

IOrderedEnumerable<KeyValuePair<string, int>> dictByFreq = words.OrderBy<KeyValuePair<string, int>, int>((KeyValuePair<string, int> kvp) =>  -kvp.Value);

它使用。net框架为你做所有的工作。单词。OrderBy接受一个Func参数,该参数提供要排序的值。使用此函数的默认值的问题是,它希望对进行排序,而您希望对进行排序。这个函数调用将完全做到这一点。它还将根据值(即特定匹配发生的频率)按降序对它们进行排序。它返回一个IOrderedEnumerable对象,该对象必须被存储。因为它是可枚举的,你甚至不需要把它放回字典里!如果以后确实需要对其进行其他操作,可以调用dictByFreq.ToList()函数,该函数返回类型为:List>的对象。

整个函数变成了

foreach (Match match in wordPattern.Matches(str))
{
    if (!words.ContainsKey(match.Value))
        words.Add(match.Value, 1);
    else
        words[match.Value]++;
}
IOrderedEnumerable<KeyValuePair<string, int>> dictByFreq = words.OrderBy<KeyValuePair<string, int>, int>((KeyValuePair<string, int> kvp) => -kvp.Value);
Hunspell hunspell = new Hunspell("en_US.aff", "en_US.dic");
StringBuilder resultSb = new StringBuilder(dictByFreq.Count);
foreach (KeyValuePair<string, int> entry in dictByFreq)
{
    resultSb.AppendLine(string.Format("{0} [{1}]", entry.Key, entry.Value));
    richTextBox2.Text = resultSb.ToString();
    bool correct = hunspell.Spell(entry.Key);
    if (correct == false)
    {
        richTextBox4.Text = entry.Key;
    }
}

您在richtextbox4上显示的内容与richtextbox2相同:)

我认为这应该可以工作:

foreach (KeyValuePair<string, int> entry in dictByFreq)
{
    resultSb.AppendLine(string.Format("{0} [{1}]", entry.Key, entry.Value));
    richTextBox2.Text = resultSb.ToString();
    bool correct = hunspell.Spell(entry.Key);
    if (correct == false)                
    {
        richTextBox4.Text += entry.Key;
    }    
}