c# - c# - 如何搜索文本文件中存在的两个或多个单词的单词

标签 c#

我有3个文本文件,即

input.txt
array1.txt
array2.txt

input.txt 文件包含如下行:

 the file in
 the computer is 
removedby user,
there are seven
 wonders in the      world 
ithink...

array1.txt 文件包括:

computer 
user 
good

array2.txt 文件包括:

seven
world 
none

我想用 array1.txt 和 array2.txt 检查 input.txt 中是否存在单词

我想说的是,例如:input.txt 中的单词与 array1.txt 中的单词匹配意味着输出必须是“computer”存在于 array1 中。如果单词与 array2.txt 匹配意味着它应该显示 array2 中存在的单词。

输出:words computer 和 user 出现在 array1 words world 中,七个出现在 array2 中

我的 C# 代码:

int count;
using (StreamReader reader = File.OpenText("C:/Users/input.txt"))
{
  string contents = reader.ReadToEnd();
  MatchCollection matches = Regex.Matches(contents, "computer", RegexOptions.IgnoreCase);
  count = matches.Count;
 }
if (count > 0)
{
    MessageBox.Show("present");
}
else
{
    MessageBox.Show("absent");
}

最佳答案

我会采用不同的方法:

  1. 要读取文件(除非它是一个需要流式处理的非常大的文件),我会使用 File.ReadAllTextFile.ReadAllLines
  2. 为了检查文本中是否存在数组中的字符串,我会使用 Contains 而不是正则表达式。
  3. 最后我会使用 linq Where检查数组中每一项的谓词的方法

所以:

var arr1 = File.ReadAllLines("array1.txt"); // Reading to get string[] - item for each line
var arr2 = File.ReadAllLines("array2.txt");
var input = File.ReadAllText("input.txt"); // Reading to get one string for all text

var arr1WordsInInput = arr1.Where(input.Contains);
var arr2WordsInInput = arr2.Where(input.Contains);

如果你想找到匹配项的所有索引,你可以使用这个问题的答案中建议的函数 Finding ALL positions of a substring in a large string in C#像这样:

var result = arr1.Select(w => new {  Word = w, Indexes = input.AllIndexesOf(w) })
                 .Where(w => w.Indexes.Any());

这将返回一个 IEnumerable,其中每个项目包含两个属性:匹配词和在 input 文本中找到它的索引

关于c# - c# - 如何搜索文本文件中存在的两个或多个单词的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46272148/

相关文章:

c# - 使用 linq 遍历大型数据库表

c# - DateTime TryParse - 将 '99' 映射到 2099,而不是 1999

c# - 将 XML 传递给 Web 服务的最佳方法?

c# - 身份验证在 IIS8.5 中安装的 Wordpress 博客的子目录中不起作用

c# - Roslyn:在单个源代码行上枚举精确的标记+琐事跨度?

c# - 如何使用DotNetOpenAuthentication获取facebook、gmail、twitter的头像?(说明内页)

c# - 哪个 .NET 集合更快 : enumerating foreach Dictionary<>. Values 或 List<>?

c# - 在 C# 中针对现有文件的 CreateNew 的 FileStream 构造函数抛出异常

c# disposing 语法

c# - StackExchange.Redis 异步调用挂起