【发布时间】:2016-01-28 08:06:32
【问题描述】:
如何将文本拆分为文本中的句子;带点、问号、感叹号等。我试图一个接一个地得到每个句子,除了引号内。
例如拆分这个:
Walked. Turned back. But why? And said "Hello world. Damn this string splitting things!" without a shame.
像这样:
Walked.
Turned back.
But why?
And said "Hello world. Damn this string splitting things!" without a shame.
我正在使用此代码:
private List<String> FindSentencesWhichContainsWord(string text, string word)
{
string[] sentences = text.Split(new char[] { '.', '?', '!' }, StringSplitOptions.RemoveEmptyEntries);
// Define the search terms. This list could also be dynamically populated at runtime.
string[] wordsToMatch = { word };
// Find sentences that contain all the terms in the wordsToMatch array.
// Note that the number of terms to match is not specified at compile time.
var sentenceQuery = from sentence in sentences
let w = sentence.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' },
StringSplitOptions.RemoveEmptyEntries)
where w.Distinct().Intersect(wordsToMatch).Count() == wordsToMatch.Count()
select sentence;
// Execute the query. Note that you can explicitly type
// the iteration variable here even though sentenceQuery
// was implicitly typed.
List<String> rtn = new List<string>();
foreach (string str in sentenceQuery)
{
rtn.Add(str);
}
return rtn;
}
但它给出的结果不是我想要的。
Walked.
Turned back.
But why?
And said "Hello world.
Damn this string splitting things!
" without a shame.
【问题讨论】:
-
您的
Split数组中有'!'字符 -
你可以测试你的字符串,如果点、感叹号等在引号内,然后跳过分割函数。