【问题标题】:Counting number of words in a text file计算文本文件中的单词数
【发布时间】:2012-11-05 23:51:14
【问题描述】:

我正在尝试计算文本文件中的单词数,即这个,开始。

这是一个字数统计程序的测试。这只是一个测试。如果你的 程序运行成功,你应该计算出有 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);
    }
} 

【问题讨论】:

    标签: c# .net regex


    【解决方案1】:

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

    int count = Regex.Matches(input, @"\b\w+\b").Count;
    

    【讨论】:

      【解决方案2】:

      这应该适合你:

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

      }

      【讨论】:

      • 为什么不StreamReader.ReadToEnd()
      • @NikoDrašković 如果文件有 1000 或 10000 或 10M 字怎么办?由于我很久以前就开始使用 C,因此我永远不会使用 ReadToEnd,这是一种习惯,但认为在我可以分块读取文件的情况下将文件中的内容读入内存并不是最佳选择。这也说明了 OP 在代码中的错误。
      • 您的代码有效,但我不明白为什么。当我只输出 fields.Length 时,它给了我一个值 3。为什么 counter+=fields.Length 给了 30,而当 counter 初始化为 0 时?
      • 如果文件是10M并且只有一行怎么办? :) 除了笑话,如果文件真的很大,我会考虑使用Michael Abrashes 方法。如果不是,我会使用ReadToEnd(),尽管您分块读取文件的观点是有效的!
      • @NikoDrašković 单行的好点:-)。真的从来没想过。我必须尝试一下。我正在考虑一个很好的旧 fscanf() 或 fgets() 之类的东西。不是那种高级文件阅读。
      【解决方案3】:

      一些提示。

      1. 如果您只有句子“hi”,您的输出会是什么?
      2. 您的计数器计算是:从 0 到 fields.Length,递增计数器。 fields.Length 和你的柜台有什么关系?

      【讨论】:

      • 1.当我在文本文件中输入“hi”时,它告诉我字数是 1。
      【解决方案4】:

      你可能遇到一次性错误,试试这样的方法

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

      直接获取数字就不需要遍历数组来统计元素了

      【讨论】:

      • 我给我的文本文件,段落被排列成3行,最后一行只包含“在这个文件中”。当我尝试 Console.WriteLine(line);在我的程序中没有其他任何东西,它只是输出“在这个文件中”。你知道为什么它只读到最后一行吗?
      • ah,k srry 我没仔细看,这是因为 read line 一次只读取一行,所以你正在阅读所有 thre 但只计算最后一个阅读
      • 我更改了我的代码,现在它是 line += sr.ReadLine + " ";现在,当我在 Console.WriteLine 上显示字符串时,它会输出整个字符串。但是,当我尝试显示 fields.Length 时,它给了我 35 的值。知道为什么吗?
      • 技术上是 29 个单词,但我们也应该将数字 30 算作一个单词,所以总共 30 个单词。
      • 如果没有看到输入,我不能说。我的猜测是您的分隔符是错误的,并且您将一些单词一分为二。尝试仅使用“”作为分隔符,看看会发生什么。查看文件并考虑 delim 是如何拆分它的。你会弄清楚的。我想你已经很接近了
      【解决方案5】:
      //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;
      
              }
      
      
          }
      }
      

      【讨论】:

      • 不要只放代码,请添加一些说明你是如何得到这个解决方案的。
      【解决方案6】:
      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);
              }
          }
      }
      

      【讨论】:

      • 用于.txt文件
      猜你喜欢
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      相关资源
      最近更新 更多