java - Counting Number of Word in Each Sentence -
i have text file in format:
word index adam 0 likes 1 2 play 3 soccer 4 0 have 1 2 study 3 4 5 exam 6
i want count number of words in each sentence. created 3 array lists 1 word index, other counting tokens in sentence, , other saving number of tokens each sentence. read above file array list , did following:
(int f=0; f<onlywordindex.size() ;f++){ if (!onlywordindex.get(f).equals("0")) { numbercounter1.add("1"); } if (onlywordindex.get(f).equals("0")) { numbercounter1.add("1"); sentencelegnth=numbercounter1.size(); numbercounter2.add(sentencelegnth); numbercounter1.clear(); } }
but think either i'm missing or complicating problem. so, in improving appreciated. thanks,
it seems logical use map in case instead of arraylist though implement in both ways.
using map:
map<string,integer> wordmap = putwordsinmap(file file); public void countwords([whatever-input-you-want]) { string sentence = [some-sentence]; string[] sensplit = sentence.split(" "); for(string s : sensplit) { if(wordmap.contains(s)) { wordmap.put(s,new integer(wordmap.get(s).intvalue + 1)); } } }
if want keep track of how many of words found in each sentence you'd add existing code:
list<string> sentencewords = new arraylist<string>(); for(string s : sensplit) { if(wordmap.contains(s)) { wordmap.put(s,new integer(wordmap.get(s).intvalue + 1)); sentencewordcount += 1; } sentencewords.add(sentencewordcount);
you implement sentence word count map...it depends context behind solution.
Comments
Post a Comment