使用 C# 从文本文件中获取单词

Getting words out of a text file with C#

我写了一个方法,可以从随机文本文件中获取以 "b" 开头的单词和 return IEnumerable。它必须以收益率 return.

工作

问题是我不知道如何结合 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();
        }
    }
}

此方法产生 returns 所有以 '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);

使用system.io.file.readalltext获取所有文本。 用“”拆分它以获得单词。 然后只需查找以 b:

开头的任何内容
var wordsThatStartWithB = System.IO.File.ReadAllText("D:\test.txt")
        .Split(char.Parse(" "))
        .Where(x => x.StartsWith("b"));

这一行将完成任务并在内部使用 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();