Получить 'N' номера предыдущих и следующих слов из искомого ключевого слова из большой строки
24 просмотра
2 ответа
44 Репутация автора
Я ищу решение, где я могу получить -nh + nth количество слов из моего искомого ключевого слова из строки
ех.
string searchString= "For several years I’ve had a little “utility” function that I’ve used in several projects that I use to convert property names into strings. One use case is for instance when mapping code to some data source or third party API that where the names are used as keys...";
string keywordToSearch="instance";
int wordsToFetch=5;
Вывод будет: Один вариант использования, например, когда отображение кода на некоторые
В настоящее время я работаю над темой интеллектуального анализа текста, в которой мне нужно извлечь файлы и найти определенное ключевое слово + его предложение из извлеченной строки. Ранее я получал первое предложение из строки всякий раз, когда получал желаемое ключевое слово. но теперь требование изменилось, как указано выше, вот фрагмент кода
using System.Linq;
using System.Text.RegularExpressions;
using System;
public class Program
{
public static void Main()
{
var sentence = "For several years I’ve had a little “utility” function that I’ve used in several projects that I use to convert property names into strings. One use case is for instance when mapping code to some data source or third party API that where the names are used as keys. The method uses “static reflection”, or rather it parses the expression tree from a lambda expression, to figure out the name of a property that the lambda expression returns the value of.Look, good against remotes is one thing, good against the living, that’s something else.";
var keyword = "instance";
var keyToSearch = new Regex("[^.!?;]*(" + keyword + ")[^.!?;]*");
var m = keyToSearch.Matches(sentence);
var result1 = Enumerable.Range(0, m.Count).Select(index => m[index].Value).ToList();
Console.WriteLine("Output:- {0} ",result1[0]);
}
}
вот выход я получил
Вывод: - Один из вариантов использования, например, при отображении кода в некоторый источник данных или сторонний API, где имена используются в качестве ключей
это дает мне первое предложение, где я получил желаемое ключевое слово, любое предложение, какие изменения я должен сделать, чтобы получить новый требуемый результат.
Автор: T. Giri Источник Размещён: 11.08.2019 07:25Ответы (2)
1 плюс
3154 Репутация автора
Как насчет этого: 1) разбить его на слова 2) найти индекс вашего keyword
и 3) взять диапазон слов, начинающихся 5
до того, как вы нашли индекс
using System;
using System.Linq;
namespace Foo
{
class Program
{
static void Main(string[] args)
{
var sentence = "For several years I’ve had a little “utility” function that I’ve used in several projects that I use to convert property names into strings. One use case is for instance when mapping code to some data source or third party API that where the names are used as keys. The method uses “static reflection”, or rather it parses the expression tree from a lambda expression, to figure out the name of a property that the lambda expression returns the value of.Look, good against remotes is one thing, good against the living, that’s something else.";
var keyword = "instance";
var words = sentence.Split(' ').ToArray(); // split into words
int index = Array.FindIndex(words, w => w.Equals(keyword)); // find the index within
// take 11 words from 5 before the index of your keyword
var r = Enumerable
.Range(index - 5, 11)
.Select(i => words[i]);
var result = string.Join(' ', r);
Console.WriteLine("Output:- {0} ", result);
Console.ReadKey();
}
}
}
Это дает желаемый результат, но не касается:
- Несколько матчей
- Соответствие на другой случай
- Возможность
IndexOutOfRangeException
при получении нужных слов
0 плюса
44 Репутация автора
благодаря @ath получил решение
using System.Linq;
using System.Text.RegularExpressions;
using System;
public class Program
{
public static void Main()
{
var sentence = "case is for instance doooo mapping code to some data source or third party API that where the names are used as keys. The method uses “static reflection”, or rather it parses the expression tree from a lambda expression, to figure out the name of a property that the lambda expression returns the value of.Look, good against remotes is one thing, good against the living, that’s something else.For several years I’ve had a little “utility” function that I’ve used in several projects that I use to convert property names into strings. One use case is for instance when mapping code to some data source or third party API that where the names are used as keys. The method uses “static reflection”, or rather it parses the expression tree from a lambda expression, to figure out the name of a property that the lambda expression returns the value of.Look, good against remotes is one thing, good against the living, that’s something else.";
var keyword = "instance";
int wordFreq = 2;
var words = sentence.Split(' ').ToArray(); // split into words
int foundndex = Array.FindIndex(words, w => w.Equals(keyword)); // find the index within
// take wordFreq words from wordFreq before the index of your keyword
var wordsArray = Enumerable
.Range((foundndex - wordFreq) > 0 ? (foundndex - wordFreq) : 0, (wordFreq*2+1 > (words.Length)-1) ? (words.Length)-1 : wordFreq*2+1 )
.Select(i => words[i]).ToArray();
var outPut = string.Join(" ", wordsArray);
Console.WriteLine("Output:- {0} ",outPut);
}
}
Надеюсь, я обработал все возможные исключения!
Автор: T. Giri Размещён: 11.08.2019 12:51Вопросы из категории :
- c# Преобразовать десятичную в двойную?
- c# Как рассчитать чей-то возраст в C #?
- c# Как вы сортируете словарь по значению?
- c# В чем разница между int и Integer в Java и C #?
- c# Как создать новый экземпляр объекта из Типа
- c# Datatable против Dataset
- text-mining Ползать в интернете
- text-mining Полнотекстовые PDF-файлы для статей PubMed
- text-mining Определить язык текста в R
- text-mining Как найти шаблон в текстовом файле, используя Python, сочетающий операции регулярных выражений и операции с файлами / файлами, и сохранить экземпляры шаблона?
- text-mining Методы извлечения локаций из текста?
- text-mining список частот слов с использованием R
- string-operations Добавьте пробел до и после всех чисел в алфавитно-цифровой строке в SQL
- string-operations C ++ новичок не подходит для 'operator-'
- string-operations Сплит струна с пружиной EL
- string-operations Scala: Int не принимает параметры при рекурсивном вызове
- string-operations r - Как отсортировать слова в строке?
- string-operations Merge CLOB into one line - ORACLE