टेक्स्ट फ़ाइल में शब्दों की संख्या कैसे गिनें?


नमस्ते
मैंने टेक्स्ट फ़ाइल पढ़ी जिसमें कई शब्द हैं, फ़ाइल की सामग्री s0 में सहेजी गई है
और मैं जानना चाहता हूं कि इसमें कितने शब्द हैं
मैंनें इस्तेमाल किया
MyWord = s0.Split(नया वर्ण[] {” }, StringSplitOptions.RemoveEmptyEntries);
MyWord स्ट्रिंग्स की सरणी है
मदद

मैंने क्या प्रयास किया है:

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

समाधान 1

इसे करने का एक तरीका यहां दिया गया है:

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

आउटपुट:

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

समाधान 2

एक सरल रेगेक्स होगा

रेगुलर एक्सप्रेशन से
\w+

जो आपको देगा

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

मिलान गिनने से आपको शब्दों की संख्या मिल जाएगी।

コメント

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