2017-12-31 15 views
1

나는 문장을 단어 배열로 나누고 각 단어를 3 개의 파일 (양수, 음수, 중성)로 검색하는 매우 기본적인 감정 분석 프로그램을 작업하고 있습니다. 각 감정이 담긴 단어는 평균 점수를 표시하고 싶습니다. 나는 1-10의 척도로 문장을 평가하고 싶다 (10은 행복하고 0은 슬프다). 중립 점수 인 5로 점수를 초기화했습니다.자바를 사용하여 텍스트 파일에서 문자열을 찾을 때 문제가 발생했습니다.

프로그램을 실행하면 결과에 5 점만 표시됩니다. 파일에 문자열을 찾는 데 문제가있는 것처럼 보입니다.

b.addActionListener(new ActionListener(){ 
     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      String str = t1.getText(); 
      Label result; 
      int score = 5; 
      String[] words = str.split("\\s+"); 

      for (int i = 0; i < words.length; i++) {      
       words[i] = words[i].replaceAll("[^\\w]", ""); 
      } 

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

       if(search_pos(words[i])){ 
        score = (score + 10)/2; 
        break; 
       } 

       if(search_neg(words[i])){ 
        score = (score + 5)/2; 
        break; 
       } 

       if(search_neu(words[i])){ 
        score = (score - 10)/2; 
        break; 
       } 
      } 


      result=new Label("score is " + score); 
      result.setBounds(50,350, 200,30); 

      f.add(result); 


     } 

    }); 



static boolean search_pos(String s){ 

    Scanner scanner=new Scanner("F:\\pos-words.txt"); 

    boolean flag = false; 

    while(scanner.hasNextLine()){ 
     if(s.equalsIgnoreCase(scanner.nextLine().trim())){ 
      // found 
      flag = true; 
     } 
    } 
    return flag; 
} 

static boolean search_neg(String s){ 

    Scanner scanner=new Scanner("F:\\neg-words.txt"); 

    boolean flag = false; 

    while(scanner.hasNextLine()){ 
     if(s.equalsIgnoreCase(scanner.nextLine().trim())){ 
      // found 
      flag = true; 
     } 
    } 
    return flag; 
} 

    static boolean search_neu(String s){ 

    Scanner scanner=new Scanner("F:\\neu-words.txt"); 

    boolean flag = false; 

    while(scanner.hasNextLine()){ 
     if(s.equalsIgnoreCase(scanner.nextLine().trim())){ 
      // found 
      flag = true; 
     } 
    } 
    return flag; 
} 

} 

도움을 주시면 감사하겠습니다.

답변

1

예를 들어 문제에 대한 목적으로, 나는 단일 파일 내에서 감정적 믹스를 제공하고 있습니다. 중립적 인 단어와 일치 할 필요는 없지만 긍정적이고 부정적인 단어는 충분하지만 원하는 경우 그 중립적 인 단어를 셀 수 있습니다. 단어들, 좋아, 그 예를 들어 보자.

먼저 점수를 포함하는 파일은 words_score.txt입니다 :

은 가정의 클래스 다음
good 8 
best 10 
awesome 9 
right 5 
correct 7 
outstanding 9 
bad -8 
worst -10 
flop -7 
wrong -6 
disgusting -9 
sucks -8 

:

package swing_practice; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class TestClass { 

    private static final File scoreFile = new File("/home/arif/workspace/swing_practice/src/swing_practice/words_score.txt"); 

    public static void main(String[] args) {   
     try{ 
      String str = purifySentence("I think what did that fellow does, is good for her but If I speak from that girl side, it's worst kind of thing."); 
      int score = 5; 
      String[] words = str.split("\\s+"); 

      for (int i = 0; i < words.length; i++) { 
       //System.out.println("Score for the word is : " + words[i] + " - " + getScore(words[i])); 
       score += getScore(words[i]); 
      } 

      //if you want with 3 files, just write three methods like getScore and append the score variable similarly as above 

      if(score < 0) 
       score = 0; 
      if(score > 10) 
       score = 10; 

      System.out.println("Score of the sentence is : " + score); 

     }catch(FileNotFoundException ioe){ 
      ioe.printStackTrace(); 
     } 

    } 

    private static String purifySentence(final String sentence){ 
     String purifiedValue = ""; 

     if(sentence.length() == 0){ 
      return ""; 
     }else{ 
      for(int i = 0; i < sentence.length(); i++){ 
       char ch = sentence.charAt(i); 
       if(Character.isAlphabetic(ch) || ch == ' ') 
        purifiedValue += String.valueOf(ch); 
      } 
     } 
     return purifiedValue; 
    } 

    private static int getScore(final String word) throws FileNotFoundException{ 
     int score = 0; 
     final Scanner scanner = new Scanner(scoreFile); 
     while (scanner.hasNextLine()) { 
      final String line = scanner.nextLine(); 
      String[] wordNScore = line.split("\t", -1); 
       if(wordNScore[0].equalsIgnoreCase(word)) { 
        score = Integer.parseInt(wordNScore[1]); 
        scanner.close(); 
        break; 
       } 
     } 
     return score; 
    } 

} 

이며 아래와 같이 출력했다 :

Score of the sentence is : 3 
+0

당신을위한 대단히 감사합니다 대답은, 나는 파일 경로 인 코드를 변경했다. 나는 그것을 "F : \\ words_score.txt"로 만들었고 결과는 다시 5입니다. 내가 무엇을 입력하든 대답은 항상 5입니다. NETBEANS에서 프로젝트를 실행 중입니다. 무엇이 문제 일 수 있습니까? –

+0

형제, 솔직히 말해서, 나는 당신의 코드를 보지 못했지만, 첫 번째 테스트에서 나는 또한 테스트 부분에서 0을 얻었고, 나는 단지 getScore 메소드 결과가 점수 = putScore (단어) 그래서 score + = getScore (word)로 정정 했으므로 코드를 제 시간에 작성하여 제가 한 것을 한 번 더 요청했습니다. 하나의 숫자 만 클릭하면 대답이 될 것입니다. 당신을 위해 그리고 다른 사람들에게도 도움이됩니다. – ArifMustafa

관련 문제