• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

kangye

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

一段英文中出现的单词的次数

前一段时间面试的时候,遇到一道面试题:求一段英文中的每个字母出现的次数。

今天我不求每个字母出现的频率,我求一段英文中每个单词出现的频率。

class Program
    {
        static void Main(string[] args)
        {
            string text = @"He was one of the best string instrument players in our town. He could not read music, but if he heard a tune a few times, he could play it";
            Dictionary<string, int> wordfrequencies = CountWords(text);
            foreach (KeyValuePair<string,int> entry in wordfrequencies)
            {
                Console.WriteLine("{0}:{1}",entry.Key,entry.Value);
            }
            Console.ReadKey();
        }
        static Dictionary<string,int> CountWords(string text)
        {
            //创建单词到频率的新映射
            Dictionary<string, int> wordfrequencies = new Dictionary<string, int>();
            //将文本分解成单词
            string[] words = Regex.Split(text, @"\W+");
            //添加或更新映射
            foreach (string word in words)
            {
                if (wordfrequencies.ContainsKey(word))
                {
                    wordfrequencies[word]++;
                }
                else
                {
                    wordfrequencies[word] = 1;
                }
            }
            return wordfrequencies;
        }
    }

  

posted on 2016-07-28 23:37  kangye  阅读(553)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3