2017-01-23 2 views
1

Итак, у меня есть эта программа-оболочка, которая позволяет мне возвращать две величины из метода.Подключение класса оболочки к другому классу

** Wrapper Class **

public class Words 
{ 

    private String leftWords; 
    private String rightWords; 

    public Words(String leftWords, String rightWords) { 
     this.leftWords = leftWords; 
     this.rightWords = rightWords; 
    } 

    public String getLeftWords() { 
     return leftWords; 
    } 

    public String getRightWords() { 
     return rightWords; 
    } 



    @Override 
    public int hashCode() 
    { 
     final int prime = 31; 
     int result = 1; 
     result = prime * result 
       + ((leftWords == null) ? 0 : leftWords.hashCode()); 
     result = prime * result 
       + ((rightWords == null) ? 0 : rightWords.hashCode()); 
     return result; 
    } 

    @Override 
    public boolean equals(Object obj) 
    { 
     if (this == obj) 
      return true; 
     if (obj == null) 
      return false; 
     if (getClass() != obj.getClass()) 
      return false; 
     Words other = (Words) obj; 
     if (leftWords == null) 
     { 
      if (other.leftWords != null) 
       return false; 
     } 
     else if (!leftWords.equals(other.leftWords)) 
      return false; 
     if (rightWords == null) 
     { 
      if (other.rightWords != null) 
       return false; 
     } 
     else if (!rightWords.equals(other.rightWords)) 
      return false; 
     return true; 
    } 
} 

Метод, который я хочу, чтобы связать это с является:

private static Map <Set<String>,Set<Words>> getLeftRightWords(LinkedHashMap<Set<String>,Set<Integer>> nnpIndexTokens, NLChunk chunk) throws FileNotFoundException 
    { 
    // Map <Set<String>,Set<Integer>> nnpMap = new LinkedHashMap<Set<String>, Set<Integer>>(); 
     Map <Set<String>,Set<Words>> contextMap = new LinkedHashMap<Set<String>, Set<Words>>(); 
     Set<Words> leftRightWords = new HashSet<Words>(); 


     //for(NLChunk chunk : sentence.getChunks()){ 

     if(chunk.getStrPostags().contains("NNP")){ 


      String leftWords = ""; 
      String rightWords = ""; 

      int chunkStartIndex = chunk.getStartIndex(); 
      int chunkEndIndex = chunk.getEndIndex(); 

      //nnpMap = getNNPs(chunk); 


      String previous = null; 
      int previousNnpEndIndex = 0; 
      int previousNnpStartIndex = 0; 


      for (Map.Entry<Set<String>, Set<Integer>> entry : nnpIndexTokens.entrySet()){ 


       for (Iterator<String> i = entry.getKey().iterator(); i.hasNext();){ 
        Set<Integer> entryIndex = null; 
        int nnpStartIndex = 0; 
        int nnpEndIndex = 0; 

        String currentElement = i.next(); 


        //Deriving values for beginning and ending of chunk 
        //and beginning and ending of NNP 

        if (!(entry.getValue().isEmpty())){ 

         if (currentElement.trim().split(" ").length > 1){ 
          entryIndex = entry.getValue(); 
          nnpStartIndex = entryIndex.iterator().next(); 
          nnpEndIndex = getLastElement(entryIndex); 

         } 

         else { 
          entryIndex = entry.getValue(); 
          nnpStartIndex = entryIndex.iterator().next(); 
          nnpEndIndex = nnpStartIndex; 
         } 

        } 

        if(!(chunkStartIndex<=nnpStartIndex && chunkEndIndex>=nnpEndIndex)){ 
         continue; 
        } 
         //Extracting LEFT WORDS of the NNP 

        //1)If another NNP is present in left words, left words of current NNP start from end index of previous NNP 
         if (previous != null && chunk.toString().substring(chunkStartIndex, nnpStartIndex).contains(previous)){ 

          int leftWordsEndIndex = nnpStartIndex; 
          int leftWordsStartIndex = previousNnpEndIndex; 


          for (NLWord nlword : chunk.getTokens()) 
          { 
           if(nlword.getIndex()>=leftWordsStartIndex 
             && nlword.getIndex()<leftWordsEndIndex) 
           leftWords+=nlword.getToken() +" "; 


          } 

          System.out.println("LEFT WORDS:" + leftWords+ "OF:"+ currentElement); 

         } 

        //2) If no left words are present  

         if (chunkStartIndex == nnpStartIndex){ 
          System.out.println("NO LEFT WORDS"); 

         } 
         //3) Normal case where left words consist of all the words left of the NNP starting from the beginning of the chunk 
         else { 


          for (NLWord nlword : chunk.getTokens()) 
          { 
           if(nlword.getIndex()>=chunkStartIndex 
             && nlword.getIndex()<nnpStartIndex) 
           leftWords+=nlword.getToken() +" "; 


          } 

          System.out.println("LEFT WORDS:" + leftWords+ "OF:"+ currentElement); 
         } 


         //Extracting RIGHT WORDS of NNP 
        if (entry.getKey().iterator().hasNext()){// entry.getKey().iterator().hasNext()){ 

          String nextElement = entry.getKey().iterator().next(); 

          //1)If another NNP is present in right words, right words of current NNP start from end index of current NNP to beginning of next NNP 
         if (nextElement !=null && nextElement != currentElement && chunk.toString().substring(entry.getValue().iterator().next(), chunkEndIndex).contains(nextElement)){ 

           int rightWordsStartIndex = entryIndex.iterator().next(); 
           int rightWordsEndIndex = entry.getValue().iterator().next(); 


           //String rightWord=""; 

           for (NLWord nlword : chunk.getTokens()) 
           { 
            if(nlword.getIndex()>=rightWordsStartIndex 
              && nlword.getIndex()<rightWordsEndIndex) 
            rightWords+=nlword.getToken() +" "; 


           } 

           System.out.println("LEFT WORDS:" + leftWords+ "OF:"+ currentElement); 
          } 
         } 

          //2) If no right words exist 
         if(nnpEndIndex == chunkEndIndex){ 
           System.out.println("NO RIGHT WORDS"); 
           //continue; 
          } 

          //3) Normal case where right words consist of all the words right of the NNP starting from the end of the NNP till the end of the chunk 
         else { 

           for (NLWord nlword : chunk.getTokens()) 
           { 
            if(nlword.getIndex()>=nnpEndIndex+1 
              && nlword.getIndex()<=chunkEndIndex) 
             rightWords+=nlword.getToken() +" "; 


           } 

           System.out.println("RIGHT WORDS:" + rightWords+ "OF:"+ currentElement); 
          } 



        if (previous == null){ 
         previous = currentElement; 
         previousNnpStartIndex = nnpStartIndex; 
         previousNnpEndIndex = nnpEndIndex; 
        } 

        Words contextWords = new Words(leftWords.toString(), rightWords.toString()); 
        leftRightWords.add(contextWords); 


       } 
       contextMap.put(entry.getKey(), leftRightWords); 
      }//nnps set 

     } 

     System.out.println(contextMap); 
     return contextMap; 
    } 

Как вы можете видеть, что я пытаюсь сделать в этом методе принимая собственное существительное и извлечение левого и правого слов этого правильного существительного. Ег для куска «поставщик решений для Род-Айленда» мой выход:

ОСТАЛИСЬ СЛОВ: сотрудник: Род-Айленд
RIGHT СЛОВО: поставщик решений OF: Род-Айленд

Теперь я хочу, чтобы поместить их в карте, где Род-Айленд является ключевым и значение для этого решения провайдера и партнера.

Когда я пытаюсь напечатать эту карту выходной получаю:

{[Род-Айленд] = [[email protected]]}

Как получить правильный результат?

+1

Я не понимаю, почему вы используете 'Set' в качестве ключа. –

+0

Я не понимаю, почему вы используете 'Set' как значение и' String', а не 'Set ' для хранения 'leftWords' и' rightWords'. –

+0

Я использовал Set раньше, но изменил его. Я могу вернуться назад, если это имеет смысл. – serendipity

ответ

0

Я не знаю, является ли это единственной проблемой, но ваш класс Words не переопределяет toString() метод.

Не уверен в вашем уровне мастерства Java. Так жаль, если я разместил то, что вам знакомо. System.out.println(...) вызывает toString() метод получения сообщения для объекта. Переопределелив по умолчанию с вашей собственной реализации

@Override 
public String toString(){ 
    return "leftWords: "+leftWords+", rightWords: "+rightWords; 
} 

Вы меняете [email protected] на свой собственный вывод.

+0

@Thomas F. Спасибо за ответ. Я бы назвал себя новичком в java. Так что вы говорите, что мне нужно прокомментировать переопределение из обертки? – serendipity

+0

Нет, вам нужно скопировать код в оболочку. И мне кажется, что вы неправильно понимаете семантику «Карта», проверьте ее. –

+0

Не могли бы вы рассказать об этом? Причина, по которой я перестала использовать набор для левого и правого слов, состоит в том, что мне нужно сопоставить эти левые и правые слова с несколькими списками слов, чтобы классифицировать собственное имя в имя, место или организацию. С набором как структурой данных мне позже нужно преобразовать его в формат строки для сопоставления. поэтому решил использовать строку из get go. Это вызовет проблему? – serendipity

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