【C#每日一题】统计单词数并找出频率最高的单词

作业1:统计出txt文本里面的单词数,并找出频率出现最高的单词是哪个?

运行结果:
在这里插入图片描述
上代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //文件打开
            //string file = System.IO.File.ReadAllLines(@"");
            int count = 0;
            string tmp = "";
            //初始化次数
            string words = "hihi hello,hihi,hello,hihi?";
            var new_i = words.Split(new char[] {
    
     ' ', ',', '.', '?' },StringSplitOptions.RemoveEmptyEntries);
            Console.Write("总的单词数量:{0}\n", new_i.Length);
            for (int i = 0; i < new_i.Length; i++)
            {
    
    
                //查询每个单词出现的次数
                var query = from key in new_i where key.ToUpperInvariant() == new_i[i].ToUpperInvariant() select key;
                int key_count = query.Count();
                if (key_count > count) {
    
    

                    count = key_count;
                    tmp = new_i[i];
                }
               
            }

            Console.Write("频率出现最高的单词是:{0}\n", tmp);
            Console.Write("次数为:{0}\n", count);
            
            Console.ReadKey();
            
        }
    }
}

========================

基础代码运行成功!通过外部打开!

创建11.txt在这里插入图片描述
通过外部打开:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //文件打开
            //string[] file_A = System.IO.File.ReadAllLines(@"C:\Users\Administrator\Desktop\11.txt");
            string file_A = System.IO.File.ReadAllText(@"C:\Users\Administrator\Desktop\11.txt");
            //Console.Write(file_A);
            int count = 0;
            string tmp = "";
            //初始化次数
            
            var new_i = file_A.Split(new char[] {
    
     ' ', ',', '.', '?' }, StringSplitOptions.RemoveEmptyEntries);
            Console.Write("总的单词数量:{0}\n", new_i.Length);
            for (int i = 0; i < new_i.Length; i++)
            {
    
    
                //查询每个单词出现的次数
                var query = from key in new_i where key.ToUpperInvariant() == new_i[i].ToUpperInvariant() select key;
                int key_count = query.Count();
                if (key_count > count) {
    
    

                    count = key_count;
                    tmp = new_i[i];
                }
               
            }

            Console.Write("频率出现最高的单词是:{0}\n", tmp);
            Console.Write("次数为:{0}\n", count);
            
            Console.ReadKey();
            
        }
    }
}

运行截图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_35230125/article/details/124828900