class CounterDict<TKey>
{
    public Dictionary<TKey, int> _dict = new Dictionary<TKey, int>();

    public void Add(TKey key)
    {
        if(_dict.ContainsKey(key))
            _dict[key]++;
        else
        {
            _dict.Add(key, 1);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        string line =  "The woods decay the woods decay and fall.";

        CounterDict<string> freq = new CounterDict<string>();
        foreach (string item in line.Split())
        {
            freq.Add(item.Trim().ToLower());
        }

        foreach (string key in freq._dict.Keys)
        {
            Console.WriteLine("{0}:{1}",key,freq._dict[key]);
        }           
    }
}

我想计算字符串中所有单词的出现次数。点击 我认为上面的代码在这个任务上会很慢,因为(查看Add函数):

    if(_dict.ContainsKey(key))
    _dict[key]++;
    else
    {
        _dict.Add(key, 1);
    }

另外,是保持 _dict __ public 的良好做法? (我认为不是。)

我应该如何修改或完全改变它来完成这项工作?

有帮助吗?

解决方案

这个怎么样:

Dictionary<string, int> words = new Dictionary<string, int>();
string input = "The woods decay the woods decay and fall.";
foreach (Match word in Regex.Matches(input, @"\w+", RegexOptions.ECMAScript))
{
    if (!words.ContainsKey(word.Value))
    {
        words.Add(word.Value, 1);
    }
    else
    {
        words[word.Value]++;
    }
}

主要观点是用正则表达式替换 .Split ,因此您不需要在内存中保留一个大的字符串数组,并且您可以一次处理一个项目。

其他提示

来自msdn文档:

    // When a program often has to try keys that turn out not to
    // be in the dictionary, TryGetValue can be a more efficient 
    // way to retrieve values.
    string value = "";
    if (openWith.TryGetValue("tif", out value))
    {
        Console.WriteLine("For key = \"tif\", value = {0}.", value);
    }
    else
    {
        Console.WriteLine("Key = \"tif\" is not found.");
    }

我自己没有测试过它,但它可能会提高你的效率。

这里是一些计算出现率的方法字符串。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top