1

我在表单和文本文件中获得了richtextBox 控件。我将文本文件获取到数组并获取richtextbox1.text到其他数组,而不是比较它并计算匹配的单词。

但例如文本文件中有两个“name”字,richtextbox 中有三个“and”字。因此,如果richtextbox的文本文件中有两个相同的单词,它不能在2之后为3或更高,它一定是错误的单词,所以它不能被计算在内。但是 HashSet 只计算唯一值而不是在文本文件中查找重复项。我想将文本文件中的每个单词与 RichTextBox 中的单词进行比较。

我的代码在这里:

        StreamReader sr = new StreamReader("c:\\test.txt",Encoding.Default);
        string[] word = sr.ReadLine().ToLower().Split(' ');
        sr.Close();
        string[] word2 = richTextBox1.Text.ToLower().Split(' ');
        var set1 = new HashSet<string>(word);
        var set2 = new HashSet<string>(word2);
        set1.IntersectWith(set2);

        MessageBox.Show(set1.Count.ToString());
4

2 回答 2

1

您需要计数相同吗?你需要数单词,然后...

    static Dictionary<string, int> CountWords(string[] words) {
        // use (StringComparer.{your choice}) for case-insensitive
        var result = new Dictionary<string, int>();
        foreach (string word in words) {
            int count;
            if (result.TryGetValue(word, out count)) {
                result[word] = count + 1;
            } else {
                result.Add(word, 1);
            }
        }
        return result;
    }
        ...
        var set1 = CountWords(word);
        var set2 = CountWords(word2);

        var matches = from val in set1
                      where set2.ContainsKey(val.Key)
                         && set2[val.Key] == val.Value
                      select val.Key;
        foreach (string match in matches)
        {
            Console.WriteLine(match);
        }
于 2009-06-11T09:15:27.307 回答
1

推断你想要:

文件:

foo
foo
foo
bar

文本框:

foo
foo
bar
bar

产生“3”(2 foos 和 1 bar)

Dictionary<string,int> fileCounts = new Dictionary<string, int>();
using (var sr = new StreamReader("c:\\test.txt",Encoding.Default))
{
    foreach (var word in sr.ReadLine().ToLower().Split(' '))
    {
        int c = 0;
        if (fileCounts.TryGetValue(word, out c))
        {
            fileCounts[word] = c + 1;
        }
        else
        {
            fileCounts.Add(word, 1);
        }                   
    }
}
int total = 0;
foreach (var word in richTextBox1.Text.ToLower().Split(' '))
{
    int c = 0;
    if (fileCounts.TryGetValue(word, out c))
    {
        total++;
        if (c - 1 > 0)
           fileCounts[word] = c - 1;                
        else
            fileCounts.Remove(word);
    }
}
MessageBox.Show(total.ToString());

请注意,这是对已读字典的破坏性修改,您可以避免这种情况(因此只需阅读一次字典)只需以相同的方式计算富文本框,然后取单个计数的最小值并将它们相加。

于 2009-06-11T10:04:20.343 回答