【解決方法】テキストファイルの単語数をカウントする方法


こんにちは
多くの単語が含まれるテキスト ファイルを読みました。ファイルの内容は 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

これを行う 1 つの方法は次のとおりです。

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

出力:

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をコピーしました