Comment compter le nombre de mots dans un fichier texte

la programmation


Bonjour
j’ai lu un fichier texte contenant beaucoup de mots, le contenu du fichier est enregistré dans s0
et je veux trouver combien de mots il contient
j’ai utilisé
MyWord = s0.Split (nouveau caractère[] { ‘ ‘ }, StringSplitOptions.RemoveEmptyEntries);
MyWord est un tableau de chaînes
aide

Ce que j’ai essayé :

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

Solution 1

Voici une façon de procéder :

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

Les sorties:

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

Solution 2

Une expression régulière plus simple serait

ExEx régulière
\w+

Ce qui te donnerait

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

Compter les correspondances vous donnerait le nombre de mots.

コメント

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