Cómo contar el número de palabras en un archivo de texto

programación


Hola
Leí un archivo de texto que tiene muchas palabras, el contenido del archivo se guarda en s0
y quiero saber cuantas palabras tiene
solía
MiPalabra = s0.Split(nuevo carácter[] { ‘ ‘ }, StringSplitOptions.RemoveEmptyEntries);
MyWord es una serie de cadenas
ayuda

Lo que he probado:

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

Solución 1

Aquí hay una forma de hacerlo:

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

Salidas:

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

Solución 2

Una expresión regular más simple sería

expresión regular
\w+

cual te daria

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

Contar las coincidencias te daría la cantidad de palabras.

コメント

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