基本上,
- 有一个句子列表。
- 有一个实体列表(基本上是特定的词)
- 用另一种方法插入数据库的sql查询
我正在寻找一种遍历句子并检查是否在每个句子中找到列表中声明的任何“实体”的方法。如果将它们添加到多维数组中,实体可以句子的格式存储,并将它们传递给 Sql 查询方法。
到目前为止,这就是我所拥有的:
List<string> sentenceList = new List<string>(new String[]
{"Gerald has a nice car", "Rachel has a cute cat"});
List<string> entityList = new List<string>(new String[]
{ "Gerald", "car", "Rachel", "cat" });
foreach (string sentence in sentenceList)
{
string currentSentence = sentence;
foreach(string entity in entityList)
if (currentSentence.Contains(entity))
{
This is where I need help with the code :)
//Add them as strings or an array and pass them to the method
//to be added in to table columns
}
基本上像:
Gerald has a nice car
Rachel has a cute cat
应存储为:
Gerald, car
Rachel, cat
有什么方法可以将句子中的每个实体添加到列表或数组或每个句子的一组字符串中,如上面的输出示例所示? (连续)
'.Contains' 可以工作,但也欢迎使用任何替代算法 :) 提前致谢
请您参考如下方法:
以下 linq 应该有所帮助:
List<string> sentenceList = new List<string>(new String[]
{"Gerald has a nice car", "Rachel has a cute cat"});
List<string> entityList = new List<string>(new String[]
{ "Gerald", "car", "Rachel", "cat" });
foreach (string sentence in sentenceList)
{
var words = sentence.Split(" ".ToCharArray());
var valid_words = words.Where (w => entityList.Any (en_li => en_li.Equals(w)));
// do something with valid_words. It's an enumerable with the words that match.
}
会得到你
for Gerald has a nice car
IEnumerable (2 items)
Gerald carfor Rachel has a cute cat
IEnumerable (2 items)
Rachel cat
