我坚持用于从句子中提取短语的实现算法。每个短语必须包含2到5个单词。例如,我有一句话'这篇文章是关于我想测试它的'。我需要从这句话中得到一个包含下一个短语的数组:
在PHP中,我从这样的代码开始:
$text = 'This text is about my wish to test it';
$words = explode(' ', $text);
// $words = ['This', 'text', 'is', 'about', 'my', 'wish', 'to', 'test', 'it']
请帮我实现主算法。它可以通过任何其他编程语言(C,Java,Python),而不仅仅是PHP。
答案 0 :(得分:2)
我需要的算法代码:
$text = 'This text is about my wish to test it';
$words = explode(' ', $text);
$wordsCount = count($words);
for ($i = 0; $i < $wordsCount; $i++) {
$window = 2;
$windowEnd = 5;
if ($i + $windowEnd > $wordsCount) {
$windowEnd = $wordsCount - $i;
}
if ($windowEnd < $window) {
break;
}
while ($window <= $windowEnd) {
for ($j = $i; $j < $i + $window; $j++) {
echo $words[$j], "\n";
}
echo "\n";
$window++;
}
}
答案 1 :(得分:1)
在Java中
read()
返回
String text = "This text is about my wish to test it";
int indexFirst = 0;
while (indexFirst > -1 && text.length() > indexFirst +1) {
int indexLast = text.indexOf(" ", indexFirst + 1);
indexLast = text.indexOf(" ", indexLast + 1);
while (indexLast > -1 && text.length() > indexLast + 1) {
System.out.println(text.substring(indexFirst, indexLast));
indexLast = text.indexOf(" ", indexLast + 1);
}
System.out.println(text.substring(indexFirst));
indexFirst = text.indexOf(" ", indexFirst + 1);
}