如何读取.txt并计算字长等。

问题描述 投票:0回答:2

我上周写了一个考试,有一个非常难解决的任务,没有得到重点.我有一个.txt与Text。

文本是这样的。

Der zerbrochne Krug, ein Lustspiel,

Heinrich von Kleist.

柏林。In der Realschulbuchhandlung. 1811.

8]PERSONEN.

WALTER, Gerichtsrath. ADAM, Dorfrichter. LICHT, Schreiber. FRAU MARTHE RULL. EVE, ihre Tochter. EVE,她的女儿。薇特-图普尔,一个男孩子 RUPRECHT,他的儿子。 FRAU BRIGITTE. EIN BEDIENTER, BÜTTEL, MÄGDE, 等等。

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

9]场景。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!");

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

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

c# streamreader
2个回答
0
投票

这就是你要找的类,希望能帮到你。

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!";

        }
    }
}

0
投票

试试下面的功能。

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

0
投票

我发现 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 是适合你的问题。


0
投票

其中一种方法是以下步骤

  1. 创建一个班级 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 它有2个作用

    1. 将属性Filename分配给输入的文件。
    2. 从路径中读取文件,并从文件中获取所有单词
    3. 找出字数,并将其插入到字典中,这样最后的字典就会有所有的<<<''>>,<<'总数'>>>记录

      //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. 创建一个 indexer 类的字符串,以获得所需的输出,打印到Console -。

        //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
© www.soinside.com 2019 - 2024. All rights reserved.