如何使用LINQ移除所有单词均属于停用词列表的字符串行?
问题描述
我有一个字符串数组,每个元素可能包含单个或多个单词。需要移除所有单词都属于停用词列表的元素,保留那些包含至少一个非停用词的元素,希望用LINQ实现。
给定输入数组:
then use then he the image and the should be in should be written
停用词数组:
string[] stopWords = {"a", "an", "x", "y", "z", "this", "the", "me", "you", "our", "we", "I", "them", "then", "ours", "more", "will", "he", "she", "should", "be", "at", "on", "in", "has", "have", "and"};
期望输出:
then use the image should be written
解决方案
核心逻辑是:对数组中的每一行,拆分单词后检查是否存在至少一个单词不在停用词列表中,满足条件的行予以保留。
为提升查询效率,先将停用词数组转换为HashSet<string>——它的Contains操作时间复杂度为O(1),远优于数组的O(n)。
完整代码示例
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { string[] input = { "then use", "then he", "the image", "and the", "should be in", "should be written" }; string[] stopWords = {"a", "an", "x", "y", "z", "this", "the", "me", "you", "our", "we", "I", "them", "then", "ours", "more", "will", "he", "she", "should", "be", "at", "on", "in", "has", "have", "and"}; var stopWordSet = new HashSet<string>(stopWords, StringComparer.OrdinalIgnoreCase); // 支持忽略大小写,按需调整 var result = input.Where(line => line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries) .Any(word => !stopWordSet.Contains(word)) ).ToArray(); // 输出结果 foreach (var line in result) { Console.WriteLine(line); } } }
代码说明
- HashSet转换:将停用词转为哈希集合,同时指定忽略大小写的比较器(不需要的话可移除第二个参数);
- LINQ筛选:
Where:遍历并筛选符合条件的行;Split:拆分每行单词,自动移除空条目(避免多余空格导致的无效字符串);Any:判断该行是否存在至少一个非停用词,是则保留该行。
内容的提问来源于stack exchange,提问作者Khalid Almannai
相关产品推荐
相关产品推荐

