Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 计算文本文件中的字数_C#_.net_Regex - Fatal编程技术网

C# 计算文本文件中的字数

C# 计算文本文件中的字数,c#,.net,regex,C#,.net,Regex,我试着从一个文本文件开始计算单词的数量,也就是这个 这是一个单词计数程序的测试。这只是一个测试。如果你的 程序运行成功,您应该计算出有30个 这个文件中的单词 我使用StreamReader将文件中的所有内容放入字符串中,然后使用.Split方法获取单个单词的数量,但在编译和运行程序时,我总是得到错误的值 using System; using System.IO; class WordCounter { static void Main() { string

我试着从一个文本文件开始计算单词的数量,也就是这个

这是一个单词计数程序的测试。这只是一个测试。如果你的 程序运行成功,您应该计算出有30个 这个文件中的单词

我使用StreamReader将文件中的所有内容放入字符串中,然后使用.Split方法获取单个单词的数量,但在编译和运行程序时,我总是得到错误的值

using System;
using System.IO;

class WordCounter
{
    static void Main()
    {
        string inFileName = null;

        Console.WriteLine("Enter the name of the file to process:");
        inFileName = Console.ReadLine();

        StreamReader sr = new StreamReader(inFileName);

        int counter = 0;
        string delim = " ,.";
        string[] fields = null;
        string line = null;

        while(!sr.EndOfStream)
        {
            line = sr.ReadLine();
        }



        fields = line.Split(delim.ToCharArray());
        for(int i = 0; i < fields.Length; i++)
        {
            counter++;
        }
        sr.Close();
        Console.WriteLine("The word count is {0}", counter);
    }
} 
使用系统;
使用System.IO;
类字计数器
{
静态void Main()
{
字符串inFileName=null;
WriteLine(“输入要处理的文件名:”);
inFileName=Console.ReadLine();
StreamReader sr=新的StreamReader(内嵌名);
int计数器=0;
字符串delim=“,”;
字符串[]字段=null;
字符串行=null;
而(!sr.EndOfStream)
{
line=sr.ReadLine();
}
fields=line.Split(delim.ToCharArray());
for(int i=0;i
一些提示

  • 如果你只有一句“嗨”,你的输出是什么
  • 您的计数器计算是:从0到
    字段。长度
    ,递增计数器。
    字段长度与您的计数器有何关联

  • 这应该适合您:

    using System;
    using System.IO;
    
    class WordCounter
    {
    static void Main()
    {
          string inFileName = null;
    
          Console.WriteLine("Enter the name of the file to process:");
          inFileName = Console.ReadLine();
    
          StreamReader sr = new StreamReader(inFileName);
    
          int counter = 0;
          string delim = " ,."; //maybe some more delimiters like ?! and so on
          string[] fields = null;
          string line = null;
    
          while(!sr.EndOfStream)
          {
             line = sr.ReadLine();//each time you read a line you should split it into the words
             line.Trim();
             fields = line.Split(delim.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
             counter+=fields.Length; //and just add how many of them there is
          }
    
    
          sr.Close();
          Console.WriteLine("The word count is {0}", counter);
    }
    

    }

    您可能会遇到一次性错误,请尝试类似的方法

        counter = 0;
        while(!sr.EndOfStream)
        {
            line = sr.ReadLine();
            fields = line.Split(delim.ToCharArray());
            counter += field.length();
        }
    

    当您可以直接获取数字时,无需迭代数组来计算元素数

    请尝试使用正则表达式,例如:

    var count = Regex.Matches(input, @"\b\w+\b").Count();
    
    //使用Linq计算文本文件中字数的简单方法
    ///www.techhowdy.com
    //Lyoid Lopes百年学院2018
    使用制度;
    使用System.Collections.Generic;
    使用System.IO;
    使用System.Linq;
    使用系统文本;
    使用System.Threading.Tasks;
    命名空间FP_WK13
    {
    静态类Util
    {
    公共静态IEnumerable GetLines(字符串yourtextfile)
    {
    TextReader=新的StreamReader(您的文本文件);
    字符串结果=string.Empty;
    弦线;
    而((line=reader.ReadLine())!=null)
    {
    收益率回归线;
    }
    reader.Close();
    }
    //字数
    公共静态int GetWordCount(字符串str)
    {         
    int字=0;
    string s=string.Empty;
    变量行=获取行(str);
    foreach(行中的var项目)
    {
    s=item.ToString();
    单词=单词+s.分割('').长度;
    }
    返回单词;
    }
    }
    }
    
    1。当我在文本文件中输入“hi”时,它告诉我字数是1。为什么不
    StreamReader.ReadToEnd()
    ?@NikoDrašković如果文件有1000、10000或10M个单词呢?因为我很久以前就开始使用C了,所以我永远不会使用ReadToEnd,这是一种习惯,但我认为在我可以分块读取文件的情况下,将文件中的内容读入内存并不是最好的选择。这也说明了OP在代码中的错误。你的代码工作正常,但我不明白为什么。当我只输出fields.Length时,它给我一个值3。当计数器被初始化为0时,计数器+=fields.Length给出了30,这是怎么回事?如果文件是10M并且只有一行呢?:)开玩笑,如果文件真的很大,我会考虑使用方法。如果不是的话,我会使用
    ReadToEnd()
    ,不过你的观点是正确的@NikoDrašković是一个很好的单点:-)。我真的没想过。我必须试一试。我在想一个好的老的fscanf()或fgets()之类的东西。不是高级文件读取。我在给我的文本文件中,段落被安排为3行,最后一行仅包含“在此文件中”。当我尝试Console.WriteLine(第行);在我的程序中,没有其他任何东西,它只是输出“在这个文件中”。你知道它为什么只读取最后一行吗?啊,k sry,我没有仔细看它,这是因为读取行一次只读取一行,所以你读取所有的内容,但只计算最后一行。我更改了代码,使它现在是line+=sr.ReadLine+”;现在,当我在Console.WriteLine上显示字符串时,它会输出整个字符串。但是,当我尝试显示fields.Length时,它给了我35的值。知道为什么吗?从技术上讲是29个单词,但我们也应该把数字30算为一个单词,所以总共30个单词。如果看不到输入,我就说不出来。我猜你的分隔符错了,你把一些单词一分为二。尝试使用“”作为分隔符,看看会发生什么。看看这个文件,想想delim是如何分割它的。你会明白的。我认为你已经非常接近了,不要只放代码,请添加一些描述你是如何得到这个解决方案的。它是针对.txt文件的
    //Easy method using Linq to Count number of words in a text file
    /// www.techhowdy.com
    // Lyoid Lopes Centennial College 2018
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace FP_WK13
    {
        static class Util
        {
    
            public static IEnumerable<string> GetLines(string yourtextfile)
            {
                TextReader reader = new StreamReader(yourtextfile);
                string result = string.Empty;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    yield return line;
                }
                reader.Close();
            }
    
    
    
            // Word Count 
    
            public static int GetWordCount(string str)
            {         
                int words = 0;
                string s = string.Empty;
                var lines = GetLines(str);
    
                foreach (var item in lines)
                {
                    s = item.ToString();
                    words = words +  s.Split(' ').Length;
    
                }
    
                return words;
    
            }
    
    
        }
    }
    
    using System.IO;
    using System;
    namespace solution
    {
        class Program
        {
            static void Main(string[] args)
            {
                var readFile = File.ReadAllText(@"C:\test\my.txt");
                var str = readFile.Split(new char[] { ' ', '\n'}, StringSplitOptions.RemoveEmptyEntries);
                System.Console.WriteLine("Number of words: " + str.Length);
            }
        }
    }