我有一个句子列表,除了书名之外,其他句子都相同。
如何循环遍历列表并排除相似之处以找到书名?
(这是一个例子,可以是任何有相似之处的短句。)
《蝇王》这本书堪称经典。
《杀死一只知更鸟》是一本经典之作。
《麦田里的守望者》这本书堪称经典。
我遇到的问题是我不能简单地使用regex
or Contains()
在句子中找到标题,因为我不知道下一个句子或书名是什么。我正在从外部来源搜索许多内容,所以我想我可以提取相似单词之间的内容。
The book named
麦田里的守望者 is a classic
.
List<string> sentences = new List<string>() { };
List<string> titles = new List<string>() { };
sentences.Add("The book named Lord of the Flies is a classic.");
sentences.Add("The book named To Kill a Mockingbird is a classic.");
sentences.Add("The book named The Catcher in the Rye is a classic.");
foreach (String title in sentences)
{
// what to do here?
// add title to titles list
}
我的想法是将列表中的所有字符串相互比较,排除字符串中的相似部分,然后剩下标题。但我不知道该怎么做。
这是一个有趣的问题,所以我稍微研究了一下并提出了以下(麻烦的)解决方案:
找到任何句子具有不同字符的第一个索引,
然后在相反的句子中做同样的事情
然后使用Substring
仅提取句子的不同部分:
List<string> ExtractDifferences(List<string> sentences)
{
var firstDiffIndex = GetFirstDifferenceIndex(sentences);
var lastDiffIndex = GetFirstDifferenceIndex(sentences.Select(s => new string(s.Reverse().ToArray())).ToList());
return sentences.Select(s => s.Substring(firstDiffIndex, s.Length - lastDiffIndex - firstDiffIndex)).ToList();
}
int GetFirstDifferenceIndex(IList<string> strings)
{
int firstDifferenceIndex = int.MaxValue;
for (int i = 0; i < strings.Count; i++)
{
var current = strings[i];
var prev = strings[i == 0 ? strings.Count - 1 : i - 1];
var firstDiffIndex = current
.Select((c, j) => new { CurrentChar = c, Index = j })
.FirstOrDefault(ci => ci.CurrentChar != prev[ci.Index])
.Index;
if (firstDiffIndex < firstDifferenceIndex)
{
firstDifferenceIndex = firstDiffIndex;
}
}
return firstDifferenceIndex;
}
我猜是GetFirstDifferenceIndex
方法可以用不同的方式编写,也许使用 linq 更好,但我没有足够的时间来使用它。
您可以在 rextester 上观看现场演示。 http://rextester.com/FXXSVN30342
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)