首頁 > 軟體

C語言每日練習之統計文字單詞數及高頻詞

2022-05-18 13:00:41

作業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:UsersAdministratorDesktop11.txt");
            string file_A = System.IO.File.ReadAllText(@"C:UsersAdministratorDesktop11.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();
            
        }
    }
}

執行截圖:

到此這篇關於C語言每日練習之統計文字單詞數及高頻詞的文章就介紹到這了,更多相關C語言統計文字單詞數內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com