【问题标题】:How to find that a text file contains a specific paragraph in c#.net如何在 c#.net 中查找文本文件包含特定段落
【发布时间】:2013-10-02 12:47:41
【问题描述】:

假设有一个包含文本的文本文件(例如:-任何网站的内容)。 现在,如果我想从文本文件中匹配作为段落的字符串 strA,即文本文件中的文本说 a.txt 是否包含字符串 strA ?

如何比较?

【问题讨论】:

  • 一般来说:文本文件的内容只是一个字符串(File.ReadAllText(path)),因此您可以删除问题的文件部分。除此之外,您的问题很难理解。也许你应该向我们展示更好的例子。此外,展示您尝试过的方法很重要,原因有两个:1. 我们看到了真正的问题 2. 我们看到您尝试过任何方法。
  • 澄清您的问题并添加您尝试过的内容。此外,包含“任何网站内容”的文本文件没有任何意义。看看这个网页。在文本文件中看起来如何?
  • @tnw:那部分很清楚,不是吗? “任何网站的内容”都是 html。
  • @TimSchmelter 可能是这样,但如果他的意思只是一堆属于网站一部分的文本,那么答案可能非常巨大。他是指 HTML 段落还是文本段落,这是模棱两可的。
  • @tnw:确实如此。但如果我必须回答这个问题,我会假设 网站内容 表示 html。如果您需要查找特定段落,则应使用 HtmlAgilityPack 解析 HTML。

标签: c# .net file-io


【解决方案1】:

我会这样做:

bool containsString  = File.ReadAllText(@"C:\test.txt").Contains("strA");

【讨论】:

  • 这里strA表示字符串strA="Its contains a long string"
【解决方案2】:

这是您正在寻找的一个非常基本的实现。需要进行大量改进。

    /// <summary>
    /// Finds the text files that contain paragraph.
    /// </summary>
    /// <param name="paragraph">The paragraph to check for.</param>
    /// <param name="textFilePaths">A list of paths to text files to check.</param>
    /// <returns></returns>
    List<string> FindFilesWithParagraph(string paragraph, List<string> textFilePaths)
    {
        List<string> foundPaths = new List<string>(); // list of paths to text files w/ paragraph

        foreach (string path in textFilePaths) // iterate through each file
        {
            if (!File.Exists(path)) // check files actually exist
                throw new ArgumentException();

            using (var sr = new System.IO.StreamReader(path))
            {
                if (sr.ReadToEnd().Contains(paragraph)) // read contents of file
                    foundPaths.Add(path); // and add it to list if it contains the paragraph
            }
        }

        return foundPaths;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 2012-09-22
    • 2012-05-22
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多