LINQ用于获取句子中的单词。

4

我有一个单词列表和一个句子列表。

我想知道哪些单词可以在哪些句子中找到。

下面是我的代码:

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

我需要的是一个元组列表,其中包含句子和在句子中找到的单词。

4
什么是实际问题? - Avi Meltser
我认为这是一个非常好的问题,但是您必须给我们一些信息,以便我们可以帮助您,例如什么是句子的定义? - sayah imad
“我需要一个元组列表”不是问题。这个想法是,你尝试做某事,如果你遇到了具体的问题,就来问。 - Andrei Dragotoniu
你好,你的问题不是很清楚,请你在问题中加入一个带有示例的 [mcve] 来说明你的问题。只需简要描述几个句子和单词以及期望的结果即可。 - Drag and Drop
2
部分匹配是否可接受?例如,“这是我的最大胜利”一句话将与“great”单词匹配。 - steve16351
显示剩余6条评论
3个回答

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>,只需要在最后一个Select中将Tuple.Create(word, item.index + 1)更改为Tuple.Create(word, item.text)即可。


4
您是想表达这个意思吗:
IEnumerable<(string, string)> query =
    from sentence in sentences
    from word in words
    where sentence.Contains(word)
    select (sentence, word);

那就这样吧:

得到的结果如下:

query


谢谢,我尝试了方法语法,但是在查询语法中更容易。 - sonyfuchs
2
反例:应该只在第一句中找到“in”单词;但您的代码也返回了第三句。Contains对于“homines”产生了误报。 - Dmitry Bychenko

3

您可以尝试这种方式,

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

1
谢谢,我尝试过使用方法语法,但是使用查询语法更容易。 - sonyfuchs
2
反例:应该只在第1个句子中找到“in”这个词;但是你的代码也返回了3号句子。 - Dmitry Bychenko
1
Homines,你是对的,我会尝试在另一个答案中解决你的问题,以防这与OP有关。 - Samuel Vidal
我最终点赞了你的回答。 - Samuel Vidal
1
var results = sentences.SelectMany(sentence => words.Where(word => sentence.Contains(word)).Select(word => (sentence, word))); 变量结果等于句子选择多个(sentences.SelectMany)其中包含单词的(Where)单词选择(Select)的句子和单词。 - Rob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接