问题描述
删除以?结尾的句子需要一些帮助或者用什么都替换它。
need some assistance with removing sentences that ends with "?" or replacing it with nothing.
推荐答案
var sampleText =
"Here are some sentences. Is this a question? It certainly is! What other ways can end a sentence? A colon perhaps: or a semi-colon; Is this a question? Duplicated";
您可以使用string.Split()分隔句子,然后将相同的数组输入另一个Split,以确定每个句子使用哪个分隔符
You can use string.Split() to separate the sentences, then feed that same array into another Split to determine which delimiter was used for each sentence
//Determine the individual sentences
var x = sampleText.Split(new[] { '?', '!', '.', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);
//You may need to add further punctuation
//Split the text again using the sentences to determine which delimiter was used
var y = sampleText.Split(x, StringSplitOptions.RemoveEmptyEntries);
//Rebuild the paragraph ignoring any sentences terminated with question marks
var newText = new StringBuilder("");
for(var i = 0; i < y.Length; i++)
{
if (y[i] != "?")
{
newText.Append(x[i]);
newText.Append(y[i]);
}
}
请注意,在我的sampleText中,我没有正确终止最后一句 - 除非你添加
Note in my sampleText I didn't terminate the last sentence properly - this will cause an exception unless you add
if (x.Length > y.Length)
newText.Append(x[x.Length - 1]);
您的评论
Your comment
我想删除整个问题行亲爱的。
i want to remove the whole question line dear.
可能暗示这些东西是文件中的单独行(为了获得准确的答案,你应该注意你怎么说出你的问题)。
在这种情况下,我使用了包含
might imply that these things are individual lines in a file (To get accurate answers you should take care in how you word your questions).
In this case I used a sample file containing
This is a statement.
This is another statement!
Is this is a question?
Are you sure that is a question?
That was a question
在这种情况下这是有效的(使用Linq)
In which case this works (uses Linq)
var f = File.ReadAllLines(@"C:\Temp\Test.txt");
f = f.Where(p => (!string.IsNullOrEmpty(p) && !p.Contains("?"))).ToArray();
如果我转储数组的内容 f
到控制台窗口我得到
If I dump the contents of the array f
to the console window I get
This is a statement.
This is another statement!
That was a question
如果您使用的是早期版本的C#而无法使用Linq,则可以使用
If you are using an earlier version of C# and cannot use Linq then this works instead
var f1 = new List<string>();
foreach (var s in f)
{
if (!string.IsNullOrEmpty(s) && !s.Contains("?"))
f1.Add(s);
}
f = f1.ToArray();
.+\?
这篇关于从文本中删除问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!