كيفية حساب freqency من كل الكلمات في نص الوثيقة ؟
-
06-07-2019 - |
سؤال
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]);
}
}
}
أريد أن حساب عدد أحداثا من كل الكلمات في سلسلة.
أعتقد البرمجية أعلاه سوف تكون بطيئة في هذه المهمة بسبب (النظر في إضافة وظيفة) :
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.");
}
لم تختبر بها نفسي ، ولكن يمكن تحسين الكفاءة الخاص بك.
هنا بعض الطرق للقيام عد حدوث السلاسل.
لا تنتمي إلى StackOverflow