Word combination

I am new to java. I need to calculate the associations of words with each other in a sentence. For example, for the sentence β€œA dog is a dog, and a cat is a cat”, the final association score will be - First row: Dog-Dog (0), Dog-is (2), Dog-a (2) Dog-i (1) Cat Dog (2)

etc.

This is a kind of development of a matrix of associations. Any suggestion on how this can be developed?

0
java count
source share
2 answers

Thanks, Roman. I can break words from sentences -

String sentence=null; String target="Dog is a Dog and Cat is a Cat"; int index = 0; Locale currentLocale = new Locale ("en","US"); BreakIterator wordIterator = BreakIterator.getWordInstance(currentLocale); //Creating the sentence iterator BreakIterator bi = BreakIterator.getSentenceInstance(); bi.setText(target); while (bi.next() != BreakIterator.DONE) { sentence = target.substring(index, bi.current()); System.out.println(sentence); wordIterator.setText(sentence); int start = wordIterator.first(); int end = wordIterator.next(); while (end!=BreakIterator.DONE){ String word = sentence.substring(start,end); if (Character.isLetterOrDigit(word.charAt(0))) { System.out.println(word); }//if (Character.isLetterOrDigit(word.charAt(0))) start = end; end = wordIterator.next(); }//while (end!=BreakIterator.DONE) index = bi.current(); } // while (bi.next() != BreakIterator.DONE) 

But did not get two other points. Thanks.

+3
source share
  • Divide the sentence into separate words.
  • Create couples.
  • Combine the same pairs.

It's simple:

 String[] words = sentence.split("\\s"); //first step List<List<String>> pairs = new ArrayList<List<String>>((int)(((words.length) / 2.0) * (words.length - 1))); for (int i = 0; i < words.length - 1; i++) { for (int j = i + 1; j < words.length; j++) { List<String> pair = Arrays.asList(words[i], words[j]); Collections.sort(pair); pairs.add(pair); } } //second step Map<List<String>, Integer> pair2count = new LinkedHashMap<List<String>, Integer>(); for (List<String> pair : pairs) { if (pair2count.containsKey(pair)) { pair2count.put(pair, pair2count.get(pair) + 1); } else { pair2count.put(pair, 1); } } //third step //output System.out.println(pair2count); 
0
source share

All Articles