如何在句子之前/之后得到一个单词 [英] how to get a word before/after in sentence
问题描述
我的文字现在文字很长,我搜索一个单词所以我想要在5个单词之后/之前得到这个单词例如
I have a text very longer now in text, I search one word so I wanna get after/before 5 word that word For example
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis venenatis erat diam, vel placerat
i search'elit'但在5个单词之前/之后根据该单词
dolor sit amet,consectetur adipiscing elit。 Duis venenatis erat diam,vel
喜欢这个
但也可能不够5个字
例如,我在文本上方搜索dolor。但是之前只有2个单词
所以
$ b $bı想得到
i search 'elit' but before/after 5 word according to that word
dolor sit amet, consectetur adipiscing elit. Duis venenatis erat diam, vel
Like this
but also can be not enough 5 word
For example I search 'dolor' above the text. but there are only 2 word before dolor
so
ı want to get
Lorem ipsum dolor sit amet, consectetur adipiscing elit
赞这样
我怎么能用C#
like this
how can i do it with C#
推荐答案
这样的东西对你有用(注意你可能也想让搜索不区分大小写) 。
Something like this might work for you (note that you might want to make the search case-insensitive as well).
using System;
using System.Collections.Generic;
using System.Linq;
namespace Words
{
class Program
{
static IEnumerable<int> IndexOf(IEnumerable<string> list, string searchItem)
{
var index = 0;
foreach (var item in list.Select(w => w.Trim('.', ',', ';', '(', ')', '[', ']'))) // Get rid of trailing full stops etc
{
if (item.Equals(searchItem))
yield return index;
++index;
}
}
static void Main(string[] args)
{
var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis venenatis erat diam, vel placerat";
var words = text.Split(' ');
var searchWord = "dolor";
// Loop here because the search word might appear more than once in the text
foreach (var index in IndexOf(words, searchWord))
{
var before = words.Take(index).Skip(index - 5).Take(5);
var after = words.Skip(index + 1).Take(5);
Console.WriteLine(String.Join(" ", before) + " " + String.Join(" ", after));
}
}
}
}
希望这有帮助,
Fredrik
Hope this helps,
Fredrik
非常感谢,
我也学到了答案,我们可以找到使用正则表达式如何?
Thank you a lot,
and also I have learnt a answer, we can find use regex how?
List<string> listSentences = new List<string>();
string pattern = "(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,10}" + word +
"(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,10}";
MatchCollection matches = Regex.Matches(text.ToLower(), pattern);
for (int i = 0; i < matches.Count; i++)
{
string s = "<ul><li>" + matches[i].ToString() + "</li></ul>";
listSentences.Add(s.Replace(word, "<span style="color: red;">"+word+"</span>"));
}</string></string>
谢谢!
thank you !
这篇关于如何在句子之前/之后得到一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!