2014-04-01 2 views
0

Итак, я пытаюсь получить пять последовательных слов. У меня есть этот вход:Получение пяти последовательных комбинаций слов

Тихий океан является самым крупным из океанических подразделений Земли

Выхода должен быть как:

Pacific 
Pacific Ocean 
Pacific Ocean is 
Pacific Ocean is the 
Pacific Ocean is the largest 
Ocean 
Ocean is 
Ocean is the 
Ocean is the largest 
Ocean is the largest of 
is 
is the 
is the largest 
is the largest of 
is the largest of the 
the 
the largest 
the largest of 
the largest of the 
the largest of the Earth's 
largest 
largest of 
largest of the 
largest of the Earth's 
largest of the Earth's oceanic 
of 
of the 
of the Earth's 
of the Earth's oceanic 
of the Earth's oceanic divisions 
the 
the Earth's 
the Earth's oceanic 
the Earth's oceanic divisions 
Earth's 
Earth's oceanic 
Earth's oceanic divisions 
oceanic 
oceanic divisions 
divisions 

Моей попытка:

public void getComb(String line) { 
    String words[] = line.split(" "); 
    int count = 0; 

    for (int i = 0; i < words.length; i++) { 
     String word = ""; 
     int m = i; 
     while (count < 5) { 
      count++; 
      word += " " + words[m]; 
      System.out.println(word); 
      m++; 
     } 
    } 
} 

Но результат неправильный! Выход:

Pacific 
Pacific Ocean 
Pacific Ocean is 
Pacific Ocean is the 
Pacific Ocean is the largest 

Как это исправить?

ответ

2

Изменить положение сниппето count = 0:

public void getComb(String line) { 
    String words[] = line.split(" "); 

    for (int i = 0; i < words.length; i++) { 
     int count = 0; // RESET COUNT 
     String word = ""; 
     int m = i; 
     while (count < 5 && m < words.length) { // NO EXCEPTION with 'm' limit 
      count++; 
      word += " " + words[m]; 
      System.out.println(word); 
      m++; 
     } 
    } 
} 
+1

Это будет бросить ArrayIndexOutOfBoundsException, когда вы достигнете последних четырех слов ... – jpw

+0

да. Я выхожу за пределы индекса 10 –

+0

Это исправлено! – Andynedine

1

Формально вы хотите найти n-grams размеров 1, 2, 3, 4 и 5 из вашей строки. Для этого можно использовать класс ShingleFilter в библиотеке Apache Lucene. Из JavaDoc:

A ShingleFilter строит черепицу (токены n-граммов) из потока токенов. Другими словами, он создает комбинации токенов как один токен. Например, предложение «пожалуйста, разделите это предложение на черепицу», можно разделить на черепицу «пожалуйста, разделите», «разделите это», «это предложение», «предложение в» и «на черепицу».

4

Использования вложенное для цикла вместо времени цикла и продвижение начала слова во внешнем контуре:

public static void getComb(String line) { 
    String words[] = line.split(" "); 

    for (int i = 0; i < words.length; i++) { 
     String word = ""; 

     for (int w = i; w < ((i + 5 < words.length) ? (i + 5) : words.length); w++) { 
      word += " " + words[w]; 
      System.out.println(word); 
     } 
    } 
} 

Примечание ((i + 5 < words.length) ? (i + 5) : words.length) в состоянии во внутреннем for-loop; это необходимо для того, чтобы вы не получить доступ к элементам за пределами массива, когда есть меньше, чем пять слов слева - без него вы получаете ArrayIndexOutOfBoundsException

+0

Работает отлично –

1

Попробуйте ниже approach..modified версию Andynedine

public void getComb(String line) 
{ 
    String words[] = line.split(" "); 

    for(int i=0;i<words.length;i++) 
    { 
     int count=0; //******* RESET CONT *****// 
     String word = ""; 
     int m=i; 
     while(count<5 && m < 10) 
     { 
      count++; 
      word += " "+words[m]; 
      System.out.println(word); 
      m++; 
     } 
    } 
} 
Смежные вопросы