分享

深入理解 c# 第三章 用Dictionary来统计文本中的单词数

 张氏家族Zhang 2018-04-25
  1. class DictionaryDemo  
  2. {  
  3.     static Dictionary<string,int> CountWords(string text)  
  4.     {  
  5.         Dictionary<string,int> frequencies;  
  6.         frequencies = new Dictionary<string,int>();  
  7.               
  8.         string[] words = Regex.Split(text, @"\W+");  
  9.               
  10.         foreach (string word in words)  
  11.         {  
  12.             if (frequencies.ContainsKey(word))  
  13.             {  
  14.                 frequencies[word]++;  
  15.             }  
  16.             else  
  17.             {  
  18.                 frequencies[word] = 1;  
  19.             }  
  20.         }  
  21.         return frequencies;  
  22.     }  
  23.   
  24.     static void Main()  
  25.     {  
  26.         string text = @"Do you like green eggs and ham?  
  27.                         I do not like them, Sam-I-am.  
  28.                         I do not like green eggs and ham.";  
  29.   
  30.         Dictionary<string, int> frequencies = CountWords(text);  
  31.         foreach (KeyValuePair<string, int> entry in frequencies)  
  32.         {  
  33.             string word = entry.Key;  
  34.             int frequency = entry.Value;  
  35.             Console.WriteLine("{0}: {1}", word, frequency);  
  36.         }  
  37.     }  
  38. }  

标题不支持<>

用Dictionary<TKey,TValule>来统计文本中的单词数

  1. Dictionary<string,int> frequencies;  

创建从单词到频率的新映射,  CountWords方法 创建 从string到int的空白映射,将统计每个单词在一段给定文本中的频率


  1. string[] words = Regex.Split(text, @"\W+");  

将文本分解成单词,用正则表达式分解单词  但最终会得到两个空字符串 文本头尾各一个,没有去管 Do 和 do 分开计数的问题


  1. if (frequencies.ContainsKey(word))  
  2.                 {  
  3.                     frequencies[word]++;  
  4.                 }  
  5.                 else  
  6.                 {  
  7.                     frequencies[word] = 1;  
  8.                 }  

添加或者更新映射  对每个单词都检查它是否已经在映射中。 如果是,就增加现有计数,否则,就为单词赋予一个初始计数1  负责递增的代码不需要执行到 int的强制类型 转换,就可以执行加法运算:取回的值在编译时是int类型。


  1. foreach (KeyValuePair<string, int> entry in frequencies)  
  2. {  
  3.     string word = entry.Key;  
  4.     int frequency = entry.Value;  
  5.     Console.WriteLine("{0}: {1}", word, frequency);  
  6. }  

打印映射中的每个键/值对  遍历一个Hashtable , Hashtable包含类似的DictionaryEntry, 其中每个条目都具有Key和Value属性

在c#1中,word和frequency都需要强制类型转换,因为Key和Value都返回 object类型, frequency还需要装箱

可以直接用entry.Key entry.Value, 因为是为了证明可以不用强制类型转换。


输入

  1. string text = @"Do you like green eggs and ham?  
  2.                 I do not like them, Sam-I-am.  
  3.                 I do not like green eggs and ham.";  

输出

Do: 1
you: 1
like: 3
green: 2
eggs: 2
and: 2
ham: 2
I: 3
do: 2
not: 2
them: 1
Sam: 1
am: 1
: 1

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多