Linq获取句子中的单词

时间:2019-06-03 11:28:05

标签: c# string linq

我有一个单词列表和一个句子列表。 我想知道在哪些句子中可以找到哪些单词

这是我的代码:

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();

我需要的是元组列表。用句子和单词在句子中找到。

3 个答案:

答案 0 :(得分:7)

首先,我们必须定义什么是单词。假设它是字母和撇号的任意组合

  Regex regex = new Regex(@"[\p{L}']+");

第二,我们应该考虑使用 case 该怎么做。让我们实现不区分大小写例程:

  HashSet<string> wordsToFind = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
    "est",
    "homines"
  };

然后我们可以使用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);

结果:

  (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

如果您想用Tuple<string, string>代替 word 句子,只需在最后一个{{1}中将Tuple.Create(word, item.index + 1)换成Tuple.Create(word, item.text) }

答案 1 :(得分:4)

你只是这个意思吗?

IEnumerable<(string, string)> query =
    from sentence in sentences
    from word in words
    where sentence.Contains(word)
    select (sentence, word);

给出:

query

答案 2 :(得分:3)

您可以尝试这种方式,

var result = from sentence in sentences
             from word in words
             where sentence.Contains(word)
             select Tuple.Create(sentence, word);