2

検索基準がある場合:She likes to watch tv

text.txtいくつかの文を含む入力ファイル、例えば:

I don't know what to do. She doesn't know that it's not good for her health. She likes to watch tv but really don't know what to say. I don't blame her, but it's not her fault. This was just a test text. This is the end.

テキストファイル内の文字列を検索し、文字列を含む文とその前後の文を返したい。

出力は次のようになります。

She doesn't know that it's not good for her health. She likes to watch tv but really don't know what to say. I don't blame her, but it's not her fault.

そのため、一致した検索語の前の文、検索語を含む文、検索語の後の文を出力します。

4

4 に答える 4

3

1 つの方法を次に示します。

string content = @"I don't know what to do. She doesn't know that it's not good for her health. She likes to watch tv but really don't know what to say. I don't blame her, but it's not her fault. This was just a test text. This is the end.";

string input = @"She likes to watch tv";
string curPhrase = string.Empty, prevPhrase = string.Empty, nextPhrase = string.Empty;

char[] delim = new char[] { '.' };
string[] phrases = content.Split(delim, StringSplitOptions.RemoveEmptyEntries);

for(int i=0; i<phrases.Length; i++){
    if(phrases[i].IndexOf(input) != -1){
        curPhrase = phrases[i];
        prevPhrase = phrases[i - 1];
        if (phrases[i + 1] != null)
            nextPhrase = phrases[i + 1];

        break;
    }
}

最初にテキスト全体を period.で分割し、それらを配列に格納してから、配列内の入力文字列を検索した後、現在、前、および次のフレーズを取り出します。

于 2012-06-10T17:54:04.120 に答える
3

このようなものはどうですか:

    string @in = @"I don't know what to do. She doesn't know that it's not good for her health. She likes to watch tv but really don't know what to say. I don't blame her, but it's not her fault. This was just a test text. This is the end.";
    string phrase = @"She likes to watch tv";


    int startIndex = @in.IndexOf(phrase);
    int endIndex = startIndex + phrase.Length;
    int tmpIndex;

    tmpIndex = @in.Substring(0, startIndex).LastIndexOf(". ");
    if (tmpIndex > -1)
    {
        startIndex = tmpIndex + 1;
        tmpIndex = @in.Substring(0, startIndex).LastIndexOf(". ");
        if (tmpIndex > -1)
        {
            startIndex = tmpIndex + 1;
            tmpIndex = @in.Substring(0, startIndex).LastIndexOf(". ");
            if (tmpIndex > -1)
            {
                startIndex = tmpIndex;
            }
        }
    }

    tmpIndex = @in.IndexOf(".", endIndex);
    if (tmpIndex > -1)
    {
        endIndex = tmpIndex + 1;
        tmpIndex = @in.IndexOf(".", endIndex);
        if (tmpIndex > -1)
        {
            endIndex = tmpIndex + 1;
        }
    }

    Console.WriteLine(@in.Substring(startIndex, endIndex - startIndex).Trim());

お探しのフレーズは「.」で区切られていると思います。このコードは、フレーズのインデックスを見つけて、前のフレーズの一致の後ろを検索し、次の文のフレーズの前を検索することによって機能します。

于 2012-06-10T17:28:37.437 に答える
2

ファイル内の文字列の最初の出現を返すString.IndexOf()( docs ) を使用します。この値を使用して、含まれているフレーズまたは文を削除できます。

int index = paragraph.IndexOf("She likes to watch tv")

次に、 を使用して境界と分割を設定し (おそらく正規表現indexで大文字とピリオドを使用)、両側の文を引き出します。

于 2012-06-10T17:11:28.217 に答える