Совпадение двух массивов в зависимости от местоположения в тексте - PullRequest
0 голосов
/ 30 сентября 2019

Я ищу способ разобрать данный текст и сопоставить два элемента из двух массивов. Первый массив содержит имена партий, и он должен соответствовать роли, следующей за текстом.

Я разбил исходный текст на массив, однако некоторые элементы в сторонах [] и ролях [] содержат несколько слов, поэтому трудно найти местоположение сторон в тексте

string text = "This is an example of the text to parse through, it has the title of role1. We want to extract data points like Party1 which is a role2 followed by Party2 which is a role3. Finally, we want to find Party3. This party is also known as role4. We want to display each party with its respective role";

string[] parties = {"Party1", "Party2", "Party3"};
string[] roles = {"role1", "role2", "role3", "role4"};

Результат: "Party1 = role2 \n Party2 = role3 \n Party3 = role4"

1 Ответ

0 голосов
/ 01 октября 2019

Один из способов сделать это - пройтись по строке и найти индекс каждой партии. Как только этот индекс найден, найдите индекс следующей роли и сохраните его в строке.

Существуют определенные улучшения, которые могут быть сделаны, но это может помочь вам начать:

static void Main(string[] args)
{
    string text = "This is an example of the text to parse through, it has the title of role1. We want to extract data points like Party1 which is a role2 followed by Party2 which is a role3. Finally, we want to find Party3. This party is also known as role4. We want to display each party with its respective role";
    string[] parties = {"Party1", "Party2", "Party3"};
    string[] roles = {"role1", "role2", "role3", "role4"};

    List<string> results = new List<string>();
    int index = 0;

    foreach (var party in parties)
    {
        index = text.IndexOf(party, index);
        if (index <= -1) continue;

        var r = roles
            .Select(role => new {Role = role, Index = text.IndexOf(role, index)})
            .Where(i => i.Index > -1)
            .OrderBy(i => i.Index)
            .First();

        results.Add(r != null ? $"{party} = {r.Role}" : $"{party} = N/A");
        index = r?.Index ?? index;
    }

    Console.WriteLine(string.Join(" \n ", results));

    GetKeyFromUser("\n\nDone! Press any key to exit...");
}

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...