我有一個單詞陣列,它可以包含一個或多個單詞。In case of one word, it's easy to remove it, but when choose to remove multiple words if they are all in the stop words list is difficult for me to figure it out. 我更喜歡用 LINQ 解決它。
想象一下,我有這個字串陣列
then use
then he
the image
and the
should be in
should be written
我只想得到
then use
the image
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"};
謝謝,
uj5u.com熱心網友回復:
解決此問題的一種方法是執行以下操作:
string[] stopWords = { "a", "an", "x", "y", "z", "this", "the", "me", "you", "our", "we", "I", "them", "ours", "more", "will", "he", "she", "should", "be", "at", "on", "in", "has", "have", "and" };
string input = """"
then use
then he
the image
and the
should be in
should be written
"""";
var array = input.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var filteredArray = array.Where(x => x.Split(' ').Any(y => !stopWords.Contains(y))).ToList();
var result = string.Join(Environment.NewLine, filteredArray);
Console.WriteLine(result);
前 2 行只是設定資料。
第三行通過在換行符處拆分將字串轉換為行陣列。(Environment.NewLine確保代碼在 linux 上也能正常作業。)
第四行通過在空格上拆分行來處理每一行(這讓我們得到了單獨的單詞),然后檢查串列中是否存在任何不存在的單詞stopWords。如果任何單詞不存在,則Where滿足條件并回傳整行filteredArray。
第五行簡單地連接所有單獨的行以形成最終result字串。
結果應如下所示:
then use
then he
the image
should be written
請注意,在您的stopWords串列中,您有單詞them但沒有then。所以第二個結果行不應該被洗掉。
uj5u.com熱心網友回復:
使用 Intersect 方法如下:
foreach (string word in WordsList)
{
List<string> splitData = word.Split(new string[] { " "}, StringSplitOptions.RemoveEmptyEntries).ToList();
bool allOfWordsIsInStopWords = splitData.Intersect(stopWords).Count() == splitData.Count();
}
uj5u.com熱心網友回復:
根據這個最初的問題描述:
我有一個單詞陣列,它可以包含一個或多個單詞。In case of one word, it's easy to remove it, but when choose to remove multiple words if they are ALL in the stop words list is difficult for me to figure it out . 我更喜歡用 LINQ 解決它。
以下代碼以粗體決議句子。
using System.Text.RegularExpressions;
string[] stopWords = { "a", "an", "x", "y", "z", "this", "the", "me", "you", "our", "we", "I", "them", "ours", "more", "will", "he", "she", "should", "be", "at", "on", "in", "has", "have", "and" };
string[] inputStrings = { "then use", "then he", "the image", "and the", "should be in", "should be written" };
var wordSeparatorPattern = new Regex(@"\s ");
var outputStrings = inputStrings.Where((words) =>
{
return wordSeparatorPattern.Split(words).Any((word) =>
{
return !stopWords.Contains(word);
});
});
foreach (var item in outputStrings)
{
Console.WriteLine(item);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/533113.html
標籤:C#林克停用词
