2015-12-30 10 views
2

Я ищу наиболее эффективный способ захватить определенное количество слов (в порядке) из строки.Захват случайной последовательности слов из строки?

Так скажем, у меня есть абзац текста:.

«Lorem Ipsum просто манекен текста печати и верстки промышленности Lorem Ipsum является стандартной текст манекен в отрасли с тех пор 1500-х годов, когда неизвестный принтер взял камбуз типа и скремблировал его, чтобы сделать типовой экземпляр, сохранившийся не только пять веков, но и прыжок в электронный набор, оставаясь практически неизменным. Он был популяризирован в 1960-х годах с выпуском листов Letraset, содержащих Lorem Ipsum и еще недавно с настольным издательским программным обеспечением, таким как Aldus PageMaker, включая версии Lorem Ipsum ».

Я хочу иметь возможность захватить переменное количество слов в случайных позициях в абзаце. Так что, если бы хотел 5 слов пример некоторых выходов может быть:

  • «выпуск Letraset листов, содержащих»
  • «Lorem Ipsum просто манекен»
  • «только пять веков, но и»

Что было бы лучшим способом сделать это?

ответ

1

Для последовательных изменений, я хотел бы сделать это:

  1. Поместите их в Array слов по split(' ')
  2. Генерирует случайное значение от 0 до длины Array минус 5 по Random
  3. Поместите их в предложение, дает некоторые пробелы.

VB версия + тестирование результат

(Это может быть то, что вы больше заинтересованы в)

Imports System 
Imports System.Text 

Public Module Module1 
    Public Sub Main() 
     Dim str As String = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." 
     Console.WriteLine(GrabRandSequence(str)) 
     Console.WriteLine(GrabRandSequence(str)) 
     Console.WriteLine(GrabRandSequence(str)) 
     Console.ReadKey() 
    End Sub 

    Public Function GrabRandSequence(inputstr As String) 
     Try 
      Dim words As String() = inputstr.Split(New Char() {" "c}) 
      Dim index As Integer 
      index = CInt(Math.Floor((words.Length - 5) * Rnd())) 
      Return [String].Join(" ", words, index, 5) 

     Catch e As Exception 
      Return e.ToString() 
     End Try 
    End Function  
End Module 

Результат

enter image description here

C# версия

string[] words = input.Split(' '); //Read 1. 
int val = (new Random()).Next(0, words.Length - 5); //Read 2. 
string result = string.Join(" ", words, val, 5); //Read 3. improved by Enigmativy's suggestion 

Дополнительные попробовать

Для случайных изменений, я хотел бы сделать это:

  1. очистить все ненужные символы (.И т.д.)
  2. поместить их в List по LINQsplit(' ')
  3. Выберите Distinct среди них LINQ (по желанию, чтобы избежать результат, как Lorem Lorem Lorem Lorem Lorem)
  4. Генерировать 5 различных случайных значений от 0 до размера List от Random (повтор выбор, когда не отчетливо)
  5. Подберите слова в соответствии с произвольными значениями из List
  6. Поместите их в предложение, задайте несколько пробелов.

Предупреждение: предложение не имеет смысла вообще!


C# версии (только)

string input = "the input sentence, blabla"; 
input = input.Replace(",","").Replace(".",""); //Read 1. add as many replace as you want 
List<string> words = input.Split(' ').Distinct.ToList(); //Read 2. and 3. 
Random rand = new Random(); 
List<int> vals = new List<int>(); 

do { //Read 4. 
    int val = rand.Next(0, words.Count); 
    if (!vals.Contains(val)) 
     vals.Add(val); 
} while (vals.Count < 5); 

string result = ""; 
for (int i = 0; i < 5; ++i) 
    result += words[vals[i]] + (i == 4 ? "" : " "); //read 5. and 6. 

Ваш результат находится в result

+0

Там нет необходимости удалять лишние символы. Задача состояла в том, чтобы возвращать последовательные слова из исходного текста, а не 5 отдельных случайных слов. И объединение строк с '+ (i == 4?" ":" ") Является странным, учитывая, что' result = String.Join ("", words); 'было бы достаточно. – Enigmativity

0
 string input = "Your long sentence here"; 
     int noOfWords = 5; 

     string[] arr = input.Split(' '); 

     Random rnd = new Random(); 
     int start = rnd.Next(0, arr.Length - noOfWords); 

     string output = ""; 
     for(int i = start; i < start + noOfWords; i++) 
      output += arr[i] + " "; 

     Console.WriteLine(output); 
+0

Не делайте '- 1' на' rnd.Next (...) ', поскольку верхняя граница является эксклюзивной. – Enigmativity

+0

Вы правы. Хороший улов :) – interceptwind

5

Сплит данные вверх пробелами, чтобы получить список слов, а затем найти случайное место, чтобы выбрать слова из (не менее 5 слов от конца), а затем присоединить слова обратно вместе.

private static readonly Random random = new Random(); 
public static void Main(string[] args) 
{ 
    var data = 
     "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; 
    Console.WriteLine(GetRandomWords(data, 5)); 
    Console.ReadLine(); 
} 

private static string GetRandomWords(string data, int x) 
{ 
    // Split data into words. 
    var words = data.Split(' '); 
    // Find a random place to start, at least x words back. 
    var start = random.Next(0, words.Length - x); 
    // Select the words. 
    var selectedWords = words.Skip(start).Take(x); 
    return string.Join(" ", selectedWords); 
} 

Пример вывода:

the 1960s with the release 
PageMaker including versions of Lorem 
since the 1500s, when an 
leap into electronic typesetting, remaining 
typesetting, remaining essentially unchanged. It 
+1

Это именно то решение, о котором я думал. Отлично сработано. – Enigmativity

0
string sentense = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; 
      string[] wordCollections = sentense.Split(' '); 
      Random rnd = new Random(); 
      int randomPos=rnd.Next(0, wordCollections.Length); 
      string grabAttempt1 = String.Join(" ", wordCollections.ToArray(), randomPos, 5); 
// Gives you a random string of 5 words    
      randomPos = rnd.Next(0, wordCollections.Length); 
      string grabAttempt2 = String.Join(" ", wordCollections, randomPos, 5); 
// Gives you another random string of 5 words 
0

Это может сделать трюк для вас

private void pickRandom() 
    { 
     string somestr = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; 
     string[] newinp = somestr.Split(' '); 
     Random rnd = new Random(); 
     int strtindex = rnd.Next(0, newinp.Length - 5); 
     string fivewordString = String.Join(" ", newinp.Skip(strtindex).Take(5).ToArray()); 
    } 
+1

Не '- 6' - это должно быть' - 5', поскольку max param в 'rnd.Next' является эксклюзивным. – Enigmativity

+0

Ohh yes @Enigmativity, Thanks –

Смежные вопросы