有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从句子中提取短语的java算法

我一直致力于实现从句子中提取短语的算法。每个短语必须包含2到5个单词。例如,我有一句话“这篇文章是关于我想测试它”。我需要从这句话中得到一个包含以下短语的数组:

  1. 本文
  2. 这篇文章是
  3. 这篇课文是关于
  4. 这篇课文是关于我的
  5. 文本是
  6. 文本是关于
  7. 文本是关于我的
  8. 文本是关于我的愿望
  9. 是关于
  10. 是关于我的
  11. 是关于我的愿望
  12. 是关于我的愿望
  13. 关于我的
  14. 关于我的愿望
  15. 关于我的愿望
  16. 关于我的考试愿望
  17. 我的愿望
  18. 我希望
  19. 我想测试一下
  20. 我想测试一下
  21. 想测试一下吗
  22. 想试试吗
  23. 检验
  24. 测试它
  25. 测试一下

在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


共 (2) 个答案

  1. # 1 楼答案

    我需要的算法代码:

    $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++;
        }
    }
    
  2. # 2 楼答案

    在爪哇

    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);
    }
    

    返回

    This text
    This text is
    This text is about
    This text is about my
    This text is about my wish
    This text is about my wish to
    This text is about my wish to test
    This text is about my wish to test it
     text is
     text is about
     text is about my
     text is about my wish
     text is about my wish to
     text is about my wish to test
     text is about my wish to test it
     is about
     is about my
     is about my wish
     is about my wish to
     is about my wish to test
     is about my wish to test it
     about my
     about my wish
     about my wish to
     about my wish to test
     about my wish to test it
     my wish
     my wish to
     my wish to test
     my wish to test it
     wish to
     wish to test
     wish to test it
     to test
     to test it
     test it