如何读取 .txt 并计算 word/length 等

How to read .txt and count word/length, etc

我上周写了一个考试,有一个非常艰巨的任务要解决,但没有抓住要点。 我有一个带有文本的 .txt。

正文是这样的:

Der zerbrochne Krug, ein Lustspiel,

von Heinrich von Kleist.

Berlin. In der Realschulbuchhandlung. 1811.

[8] PERSONEN.

WALTER, Gerichtsrath. ADAM, Dorfrichter. LICHT, Schreiber. FRAU MARTHE RULL. EVE, ihre Tochter. VEIT TÜMPEL, ein Bauer. RUPRECHT, sein Sohn. FRAU BRIGITTE. EIN BEDIENTER, BÜTTEL, MÄGDE, etc.

Die Handlung spielt in einem niederländischen Dorfe bei Utrecht.

[9] Scene: Die Gerichtsstube. Erster Auftritt.

我用这段代码得到了 Main:

var document = new Document("Text.txt");

            if (document.Contains("Haus") == true)
                Console.WriteLine(document["Haus"]); // Word: haus, Frequency.: 36, Length: 4
            else
                Console.WriteLine("Word not found!");

现在我不得不写一个 class 来帮助上面的代码工作。 有没有人知道如何解决这个问题并帮助年轻的商业信息学学生理解它是如何工作的? 通常 StreamReader 对我来说很容易,但在这种情况下对我来说不可能...

非常感谢你们所有人的爱和健康,你们试图帮助我。

试试下面的函数:

 private bool FindWord( string SearchWord)
        {
            List<string> LstWords = new List<string>();
            string[] Lines = File.ReadAllLines("Path of your File");
            foreach (string line in Lines )
            {
                string[] words = line.Split(' ');
                foreach (string  word in words )
                {
                    LstWords.Add(word);
                }
            }
            // Find word set word to upper letters and target word to upper  
            int index = LstWords.FindIndex(x => x.Trim ().ToUpper ().Equals(SearchWord.ToUpper ()));

            if (index==-1)
            {
                // Not Found
                return false;
            }
            else
            {
                //word found 
                return true;
            }         
        }

我发现 Regex 可能是解决此问题的好方法:

        var ms = Regex.Matches(textToSearch, wordToFind, RegexOptions.IgnoreCase);
        if (ms.Count > 0)
        {
            Console.WriteLine($"Word: {wordToFind} Frequency: {ms.Count} Length: {wordToFind.Length}");
        }
        else
        {
            Console.WriteLine("Word not found!");
        }

Regex 在命名空间中:

using System.Text.RegularExpressions;

您需要设置适合您的问题的RegexOptions

嗯,这就是您要找的 class,希望这对您有所帮助。

class Document : Dictionary<string, int>
{
    private const char WORDSPLITTER = ' ';
    public string Filename { get; }

    public Document(string filename)
    {
        Filename = filename;
        Fill();
    }

    private void Fill()
    {
        foreach (var item in File.ReadLines(Filename))
        {
            foreach (var word in item.Split(WORDSPLITTER))
            {
                if (ContainsKey(word))
                    base[word] += 1;
                else
                    Add(word, 1);
            }
        }
    }

    public bool Contains(string word) => ContainsKey(word);

    public new string this[string word]
    {
        get
        {
            if (ContainsKey(word))
                return $"Word: {word}, frequency: {base[word]}, Length: {word.Length}";
            else
                return $"Word {word} not found!";

        }
    }
}

其中一种方法是以下步骤-

  1. 创建具有以下属性的 class Document -

       //Contains file name
        public string FileName { get; set; }
        //Contains file data
        public string FileData { get; set; }
        //Contains word count
        public int WordCount { get; set; }
        //Holds all the words
        public Dictionary<string, int> DictWords { get; set; } = new Dictionary<string, int>();
    
  2. 定义做两件事的 constructor -

    1. 将 属性 文件名分配给传入文件
    2. 从路径中读取文件,得到文件中的所有单词
    3. 找到字数并将其插入词典,因此最终词典将 拥有所有 <<<'word'>>, <<'TotalCount'>>> 记录

      //Constructor
      public Document(string fileName)
      {
      //1/ Assign File Name name troperty
      FileName = fileName;
      
      //2. Read File from the Path
      string text = System.IO.File.ReadAllText(fileName, Encoding.Default);
      string[] source = text.Split(new char[] { '.', '!', '?', ',', '(', ')', '\t', '\n', '\r', ' ' }, 
          StringSplitOptions.RemoveEmptyEntries);
      
      //3. Add the counts to Dictionary
      foreach (String word in source)
      {
          if (DictWords.ContainsKey(word))
          {
              DictWords[word]++;
          } else
          {
              DictWords[word] = 1;
          }
      
      }
      

      }

  3. 创建“Contains”方法,用于检查单词是否存在或 不在文档中-

       //4. Method will return true /false based on the existence of the key/word.
        public bool Contains(string word)
        {
            if (DictWords.ContainsKey(word))
            {
                return true;
            }
            else
            {
                return false;
            }
    
        }
    
  4. 为 class 创建一个 indexer 字符串以获得要打印到
    的所需输出 控制台-

        //4. Define index on the word.
        public string this[string word]
        {
            get
            {           
                if (DictWords.TryGetValue(word, out int value))
                {
                   return $"Word: {word}, Frequency.:{value}, Length: {word.Length}";                   
                }
    
                return string.Empty;
             }
        }
    

测试:

           var document = new Document(@"Text.txt");
           if (document.Contains("BEDIENTER") == true)
                Console.WriteLine(document["BEDIENTER"]); 
            else
                Console.WriteLine("Word not found!");

           //Output
           // Word: BEDIENTER, Frequency.:1, Length: 9