【问题标题】:Find string in txt file using a list c# [closed]使用列表c#在txt文件中查找字符串[关闭]
【发布时间】:2017-11-05 18:20:57
【问题描述】:

我试图找出.txt 文件是否包含存储在名为Abreviated 的列表中的单词。该列表通过从csv 文件中读取值来填充,如下所示;

StreamReader sr = new StreamReader(@"C:\textwords.csv");
string TxtWrd = sr.ReadLine();
while ((TxtWrd = sr.ReadLine()) != null)
        {
            Words = TxtWrd.Split(Seperators, StringSplitOptions.None);
            Abreviated.Add(Words[0]);
            Expanded.Add(Words[1]);
        }

我想使用这个列表来检查.txt 文件是否包含列表中的任何单词。正在使用streamreader 读取.txt 文件并存储为字符串FileContent。我必须尝试查找匹配项的代码如下;

if (FC.Contains(Abreviated.ToString()))
        {
            MessageBox.Show("Match found");

        }
        else
        {
            MessageBox.Show("No Match");

        }

这将始终返回 else 语句,即使其中一个单词在文本文件中。

关于如何使它工作的任何建议?

提前致谢!

【问题讨论】:

  • 什么是输入(csv文件)?
  • 什么是Abreviated?如果那是List<string>,那么您认为Abreviated.ToString() 是什么?提示:它不是包含列表中所有项目的字符串...
  • 顺便问一下,你是不是故意跳过文件的第一行?
  • 这是学习How To Debug的绝佳机会。
  • 确实,调试一下,看看List<string>.ToString() 给了你什么。正如我所暗示的,它不是你认为的那样,它不是对你的目的有用。另一个提示:您可以遍历一个列表并检查该条目是否在另一个列表中。

标签: c# string list


【解决方案1】:

您可以使用key-value pair 数据结构将缩写词和相应的完整词存储为键值对。在 C# 中,Dictionary 具有用于存储键值对的通用实现。

我已经重构了您的代码,使其易于重用。

internal class FileParser
{
    internal Dictionary<string, string> WordDictionary = new Dictionary<string, string>();

    private string _filePath;
    private char Seperators => ',';
    internal FileParser(string filePath)
    {
        _filePath = filePath;
    }

    internal void Parse()
    {
        StreamReader sr = new StreamReader(_filePath);
        string TxtWrd = sr.ReadLine();
        while ((TxtWrd = sr.ReadLine()) != null)
        {
            var words = TxtWrd.Split(Seperators, StringSplitOptions.None);
            //WordDictionary.TryAdd(Words[0], Words[1]); // available in .NET corefx https://github.com/dotnet/corefx/issues/1942
            if (!WordDictionary.ContainsKey(words[0]))
                WordDictionary.Add(words[0], words[1]);
        }
    }

    internal bool IsWordAvailable(string word)
    {
        return WordDictionary.ContainsKey(word);
    }
}

现在,您可以通过以下方式在程序集中重用上述类:

public class Program
    {
        public static void Main(string[] args)
        {
            var fileParser = new FileParser(@"C:\textwords.csv");
            if(fileParser.IsWordAvailable("abc"))
            {
                MessageBox.Show("Match found");
            }
            else
            {
                MessageBox.Show("No Match");
            }
        }
    }

【讨论】:

  • 感谢您的回答!我看过这个,internal class FileParser 是一个单独的类还是包含在主程序中?我也收到了StringSplitOptionsTryadd 的错误,但是 VS 没有任何用处,为什么它会标记这个。
  • @bdg :为了可重用性,FileParser 应该是单独的类。您使用的是什么类型的Seperators,因为根据其类型,可以使用不同的Split 重载方法。关于TryAdd,添加了.NET coreFx。我将添加另一种添加键值的方法。
  • 我已经更新了FileParser 实现
  • 太棒了!感谢您清除它。替代方案已经奏效,在 .NET corefx 上阅读了错误,感谢您的帮助
【解决方案2】:

您正在将整个文件的内容与一组单词的字符串表示形式进行比较。您需要将文件内容中找到的每个单词与您的缩写列表进行比较。您可以进行比较的一种方法是将文件内容拆分为单个单词,然后根据您的缩写列表逐个查找这些单词。

string[] fileWords = FC.Split(Separators, StringSplitOptions.RemoveEmptyEntries);

bool hasMatch = false;
for(string fileWord : fileWords)
{
    if(Abbreviated.Contains(fileWord))
    {
        hasMatch = true;
        break;
    }
}

if (hasMatch)
{
    MessageBox.Show("Match found");

}
else
{
    MessageBox.Show("No Match");
}

我建议将您的缩写集合切换为 HashSet 或字典,其中还包含您匹配的缩写扩展文本。此外,可能还有其他方法可以使用正则表达式进行搜索。

【讨论】:

    【解决方案3】:

    我不确定你的一些变量是什么,所以这可能与你所拥有的略有不同,但提供相同的功能。

     static void Main(string[] args)
            {
                List<string> abbreviated = new List<string>();
                List<string> expanded = new List<string>();
    
                StreamReader sr = new StreamReader("textwords.csv");
                string TxtWrd = "";
                while ((TxtWrd = sr.ReadLine()) != null)
                {
                    Debug.WriteLine("line: " + TxtWrd);
                    string[] Words = TxtWrd.Split(new char[] { ',' } , StringSplitOptions.None);
                    abbreviated.Add(Words[0]);
                    expanded.Add(Words[1]);
                }
    
                if (abbreviated.Contains("wuu2"))
                {
                    //show message box
                } else
                {
                    //don't
                }
    
            }
    

    正如其中一个 cmets 所述,Dictionary 可能更适合于此。

    这假定您文件中的数据采用以下格式,每行都有一个新集。

    wuu2,你在做什么

    【讨论】:

      【解决方案4】:

      如果您只想检查文本文件是否包含列表中的单词,您可以将文件的全部内容读入字符串(而不是逐行),在分隔符上拆分字符串,然后检查文本文件中的单词与您的单词列表的交集是否有任何项目:

      // Get the "separators" into a list
      var wordsFile = @"c:\public\temp\textWords.csv"; // (@"C:\textwords.csv");
      var separators = File.ReadAllText(wordsFile).Split(',');
      
      // Get the words of the file into a list (add more delimeters as necessary)
      var txtFile = @"c:\public\temp\temp.txt";
      var allWords = File.ReadAllText(txtFile).Split(new[] {' ', '.', ',', ';', ':', '\r', '\n'});
      
      // Get the intersection of the file words and the separator words
      var commonWords = allWords.Intersect(separators).ToList().Distinct();
      
      if (commonWords.Any())
      {
          Console.WriteLine("The text file contains the following matching words:");
          Console.WriteLine(string.Join(", ", commonWords));
      }
      else
      {
          Console.WriteLine("The file did not contain any matching words.");
      }
      
      Console.Write("\nDone!\nPress any key to exit...");
      Console.ReadKey();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-26
        • 1970-01-01
        • 2015-04-05
        • 1970-01-01
        相关资源
        最近更新 更多