2017-05-14 16 views
2

저는 사용자가 필드에 텍스트를 입력하고 프로그램이 모든 텍스트를 실행하고 가장 일반적인 단어가 무엇인지 식별 ​​할 수있는 소프트웨어 응용 프로그램을 만드는 Java에 매우 익숙합니다. 순간, 내 코드는 다음과 같습니다사용자 입력에서 가장 일반적인 단어를 찾습니다.

JButton btnMostFrequentWord = new JButton("Most Frequent Word"); 
btnMostFrequentWord.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
    String text = textArea.getText(); 
    String[] words = text.split("\\s+"); 
    HashMap<String, Integer> occurrences = new HashMap<String, Integer>(); 
    for (String word : words) { 
     int value = 0; 
     if (occurrences.containsKey(word)) { 
     value = occurrences.get(word); 
     } 
     occurrences.put(word, value + 1); 
    } 

    JOptionPane.showMessageDialog(null, "Most Frequent Word: " + occurrences.values()); 
    } 
} 

이 단지 단어의 값이 무엇인지 인쇄,하지만 난 그게 번호를 하나의 가장 일반적인 단어 대신 무엇인지 말해 싶습니다. 어떤 도움이라도 대단히 감사 할 것입니다.

답변

1

아래에 당신이 값을 기준으로지도를 정렬 할 수 있습니다처럼 다음 값으로 정렬 된 항목을 반전 시도하고를 선택할 수 있습니다 먼저.

for (String word: words) { 
    int value = 0; 
    if (occurrences.containsKey(word)) { 
     value = occurrences.get(word); 
    } 
    occurrences.put(word, value + 1); 
} 

Map.Entry<String,Integer> tempResult = occurrences.entrySet().stream() 
       .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) 
       .findFirst().get(); 
JOptionPane.showMessageDialog(null, "Most Frequent Word: " + tempResult.getKey()); 
0

당신은지도 발생을 반복하고 최대를 찾거나 은 그냥 for 루프 후

String text = textArea.getText();; 
String[] words = text.split("\\s+"); 
HashMap<String, Integer> occurrences = new HashMap<>(); 
int mostFreq = -1; 
String mostFreqWord = null; 

for (String word : words) { 
    int value = 0; 
    if (occurrences.containsKey(word)) { 
     value = occurrences.get(word); 
    } 
    occurrences.put(word, value + 1); 

    if (value > mostFreq) { 
     mostFreq = value; 
     mostFreqWord = word; 
    } 
} 

JOptionPane.showMessageDialog(null, "Most Frequent Word: " + mostFreqWord); 
0

나는이

int max = 0; 
String a = null; 
for (String word : words) { 
    int value = 0; 
    if(occurrences.containsKey(word)){ 
     value = occurrences.get(word); 
    } 
    occurrences.put(word, value + 1); 
    if(max < value+1){ 
     max = value+1; 
     a = word; 
    } 
} 
System.out.println(a); 

당신은 그것을 정렬 할 수 있고,이 솔루션은 훨씬 더 짧은 것처럼 뭔가를 할 것입니다,하지만 난이 빠르게 실행 생각합니다. 가장 일반적인 단어가 정렬 후 words.get(0)에 저장됩니다

List<String> words = Arrays.asList(text.split("\\s+")); 

Collections.sort(words, Comparator.comparingInt(word -> { 
    return Collections.frequency(words, word); 
}).reversed()); 

:

0

자바에 더 익숙한 누군가를 위해, 여기에 자바 (8)와 함께 할 수있는 아주 쉬운 방법입니다.