Cách đếm số từ trong file văn bản

lập trình


Xin chào
tôi đọc tệp văn bản có nhiều từ nội dung của tệp được lưu trong s0
và tôi muốn tìm xem nó có bao nhiêu từ
tôi đã sử dụng
MyWord = s0.Split(ký tự mới[] { ‘ ‘ }, StringSplitOptions.RemoveEmptyEntries);
MyWord là mảng chuỗi
giúp đỡ

Những gì tôi đã thử:

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");
        }

Giải pháp 1

Đây là một cách để làm điều đó:

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.");

Đầu ra:

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

Giải pháp 2

Một biểu thức chính quy đơn giản hơn sẽ là

RegEx
\w+

Cái nào sẽ cho bạn

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

Đếm các kết quả phù hợp sẽ cho bạn số lượng từ.

コメント

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