【问题标题】:Getting words out of a text file with C#使用 C# 从文本文件中获取单词
【发布时间】:2015-05-19 08:10:10
【问题描述】:

我编写了一个方法,它从随机文本文件中获取以“b”开头的单词并返回一个 IEnumerable。它必须与收益回报一起使用。

问题是我不知道如何结合 Ienumerable 和 yield return 编写这样的方法。

这是我到目前为止得到的: GetWords.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace week3
         {
             class GetWords : IEnumerable<String>
    {

        private String[] getWords;

        public GetWords()
        {

        }

        public IEnumerator<String> GetEnumerator()
        {
            try
            {
                String path = @"C:\Users\Lilly\Downloads\randomtext.txt";
                foreach (String word in getWords (path, s => s.StartsWith("b")))
                 Console.Write("{0}; ", word);


            }
            catch (Exception ex)
            {
                Console.WriteLine("wrong path");

            }
            yield return word;
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

【问题讨论】:

  • 你忘了说我猜的问题。
  • 你需要在try块外声明和初始化你的变量word才能在try块外返回它。
  • 为什么需要yield?使用LINQ,您只需返回.Where() 调用即可。

标签: c# text-files ienumerable yield-return


【解决方案1】:

此方法 yield 返回所有以 'b' 开头的单词

public static IEnumerable<string> ReadWords(this FileInfo fileInfo, Encoding enc)
{
    using (var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.None))
    {
        using (var reader = new StreamReader(stream))
        {
            do
            {
                string[] line = reader.ReadLine().Split(' ');
                foreach (string word in line)
                {
                    if (word.StartsWith('b'))
                    yield return word;
                }

            } while (!reader.EndOfStream);
        }
    }
}

用法

string path = @"C:\Users\Lilly\Downloads\randomtext.txt";
var result = ReadWords(path, Encoding.Default);

【讨论】:

    【解决方案2】:

    这一行将完成任务并在内部使用 yield return:

    var allWordsStartingWithB = File.ReadLines(filePath).SelectMany(line => line.Split(' ')).Where(word => word.StartsWith("b"));
    

    当然,如果你想这样,你可以更明确地使用 yield return,虽然这有点没用:

    public static IEnumerable<string> ReadWordsStartingWithB(string filePath)
    {
        var allWordsStartingWithB = File.ReadLines(filePath).SelectMany(line => line.Split(' ')).Where(word => word.StartsWith("b"));
        foreach(var wordWithB in allWordsStartingWithB)
            yield return wordWithB;
    }
    

    ReadAllText 方法不同,ReadLines 也返回一个 IEnumerable。优点:除非需要,否则该方法不会读取整个文件。因此,如果您只想要以 b 开头的前 5 个单词,您可以这样做,并且只会读取文件所需的行而不是整个文件:

    var first5Words = ReadWordsStartingWithB("\folder\subfolder\textFile.txt").Take(5).ToArray();
    

    【讨论】:

      【解决方案3】:

      使用 system.io.file.readalltext 获取所有文本。 将其拆分为“”以获取单词。 然后只需查找以 b 开头的任何内容:

      var wordsThatStartWithB = System.IO.File.ReadAllText("D:\\test.txt")
              .Split(char.Parse(" "))
              .Where(x => x.StartsWith("b"));
      

      【讨论】:

      • 为什么要使用char.Parse(" ")?只需使用单引号来定义char: 即。 ' '.
      • 我不知道。非常感谢您的评论,FrankerZ!
      猜你喜欢
      • 2017-08-30
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多