Cara menghitung jumlah kata dalam file teks

pemrograman


Halo
saya membaca file teks yang memiliki banyak kata, isi file disimpan di s0
dan saya ingin mengetahui berapa banyak kata yang dimilikinya
saya menggunakan
MyWord = s0.Split(karakter baru[] { ‘ ‘ }, StringSplitOptions.RemoveEmptyEntries);
MyWord adalah serangkaian string
membantu

Apa yang saya coba:

StreamReader sr;
        string[] MyWord = new string[4096];

        private void FormLoad(object sender, EventArgs e)
        { 
            int i, j, count=0;
for (i = 0; i < 4096; i++) MyWord[i] = "";// string.Empty;
            string s0 = sr.ReadToEnd();
            MyWord = s0.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            sr = new StreamReader(fsr, System.Text.Encoding.Default);
            count = 0;
            for (i = 0; i < 4096; i++)
            {
                if (MyWord[i] != "")//'type of error =Index was outside the bounds of the array.'

                {
                    MessageBox.Show("MyWord["+i.ToString()+"]= "+MyWord[i],"count="+count.ToString());
                    count++;
                }
                else break;
            }
           MessageBox.Show(count.ToString() , "count");
        }

Solusi 1

Inilah salah satu cara untuk melakukannya:

C#
using System.Text.RegularExpressions;

string text = "The quick brown, and lazy, fox jumped over the tall-green fence!\r\n What a sight it was. ";

int WordCount = Regex.Matches(text, @"\b[A-Za-z0-9]+\b").Count;
int ParagraphCount = Regex.Matches(text, @"[^\r\n]*[^ \r\n]+[^\r\n]*((\r|\n|\r\n)[^\r\n]*[^ \r\n]+[^\r\n]*)*").Count + 1;

Console.WriteLine(text);
Console.WriteLine($"contains {WordCount} words and {ParagraphCount} paragraphs.");

Keluaran:

The quick brown, and lazy, fox jumped over the tall-green fence!
 What a sight it was.
contains 17 words and 2 paragraphs.

Solusi 2

Regex yang lebih sederhana adalah

RegEx
\w+

Yang akan memberi Anda

The
quick
brown
and
lazy
fox
jumped
over
the
tall
green
fence
What
a
sight
it
was

Menghitung kecocokan akan memberi Anda jumlah kata.

コメント

タイトルとURLをコピーしました