我正在嘗試計算從'句子'數組列表中每個句子出現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