c# - 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();
我需要的是一个元组列表。随着句子和单词,在句子中找到了。
解决方案
首先,我们必须定义什么是 word。让它是字母和撇号的任意组合。
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>
为Tuple.Create(word, item.index + 1)
Tuple.Create(word, item.text)
Select
推荐阅读
- c# - 检查一组位标志是否包括至少一个其他位标志的标志
- sql - 如何在 CMD 中运行 sql 命令时配置 SQL 凭据
- r - renderUI 在渲染之前不会被评估
- python - 试图只获取两个强标签之间的文本
- pyspark - 如何遍历现有的多个 pyspark 数据帧并添加包含计算的列
- python - 无法为 python3 macos mojave 安装 pip
- javascript - JavaScript 计算出错(参考之前的计算)
- excel - 如何在切片器中仅取消选择一个特定项目
- perl - Perl 在字符串中附加一个子字符串
- javascript - 使用flask-bootstrap时将SelectField值从javascript传递到flask