我正在尝试计算从'句子'数组列表中每个句子出现uniqueBagOfWords的每个单词的次数。如何计算每个单词出现多少次?
uniqueBagOFwords = [我一样,来,玩,网球,认为,足球,需求大,变化]
我希望能够指望从uniqueBagOfWords一个字有多少次出现在每个句子....目前,我只能在单词出现的位置添加1,但我想添加它出现的次数。目前,它打印出这一点:
我喜欢打网球= 1111100000
我认为足球需要大的变化= 1000011111
我喜欢足球足球= 1100001000
我将如何改变这个代码,以便它打印出以下..
我喜欢打网球= 1111100000
我觉得足球需要大的变化= 1000011111
我喜欢足球足球= 1100002000
public static void main(String[] args) {
List<String> sentences = new ArrayList<String>();
sentences.add("i like to play tennis");
sentences.add("i think football needs big changes");
sentences.add("i like football football");
List<String[]> bagOfWords = new ArrayList<String[]>();
for (String str : sentences) {
bagOfWords.add(str.split(" "));
}
Set<String> uniqueBagOfWords = new LinkedHashSet<String>();
for (String[] s : bagOfWords) {
for (String ss : s)
for (String st : ss.split(" "))
if (!uniqueBagOfWords.contains(st))
uniqueBagOfWords.add(st);
}
for (String s : sentences) {
StringBuilder numOfOccurences = new StringBuilder();
int count = 0;
for (String word : uniqueBagOfWords) {
if (s.contains(word)) {
numOfOccurences.append(count+1);
} else {
numOfOccurences.append("0");
}
}
System.out.println(s + " = " + numOfOccurences);
}
}
你能有点用你的问题是什么更直接? – Javant
您是否想过您不是第一个尝试这样做的人? – shmosel