我有一个单词表和一个句子表。我想知道哪些话可以在其中找到句子。
这是我的代码:
List<string> sentences = new List<string>();
List<string> words = new List<string>();
sentences.Add("Gallia est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur.");
sentences.Add("Alea iacta est.");
sentences.Add("Libenter homines id, quod volunt, credunt.");
words.Add("est");
words.Add("homines");
List<string> myResults = sentences
.Where(sentence => words
.Any(word => sentence.Contains(word)))
.ToList();
Run Code Online (Sandbox Code Playgroud)
我需要的是元组列表。在句子中找到单词和单词。
首先,我们必须定义什么是word。使其为字母和撇号的任意组合。
Regex regex = new Regex(@"[\p{L}']+");
Run Code Online (Sandbox Code Playgroud)
第二,我们应该考虑如何处理案例。让我们实现不区分大小写的例程:
HashSet<string> wordsToFind = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
"est",
"homines"
};
Run Code Online (Sandbox Code Playgroud)
然后我们可以使用Regex匹配句子中的单词,使用Linq查询句子:
码:
var actualWords = sentences
.Select((text, index) => new {
text = text,
index = index,
words = regex
.Matches(text)
.Cast<Match>()
.Select(match => match.Value)
.ToArray()
})
.SelectMany(item => item.words
.Where(word => wordsToFind.Contains(word))
.Select(word => Tuple.Create(word, item.index + 1)));
string report = string.Join(Environment.NewLine, actualWords);
Console.Write(report);
Run Code Online (Sandbox Code Playgroud)
结果:
(est, 1) // est appears in the 1st sentence
(est, 2) // est appears in the 2nd sentence as well
(homines, 3) // homines appears in the 3d sentence
Run Code Online (Sandbox Code Playgroud)
如果你想Tuple<string, string>对单词,句子,只是改变Tuple.Create(word, item.index + 1)了Tuple.Create(word, item.text)过去Select