【发布时间】:2016-08-12 14:51:39
【问题描述】:
我正在尝试计算 uniqueBagOfWords 中的每个单词在 'sentences' 数组列表中的每个句子中出现的次数。
uniqueBagOFwords = [i, like, to, play, 网球, think, football, needs, big, changes]
我希望能够计算 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);
}
}
【问题讨论】:
-
您能更直接一点地了解您的问题吗?
-
你有没有想过你不是第一个尝试这样做的人?
标签: java string arraylist stringbuilder word-count