早上好
我写了一个函数来计算一个术语的频率:
public static int tfCalculator(String[] totalterms, String termToCheck) {
int count = 0; //to count the overall occurrence of the term termToCheck
for (String s : totalterms) {
if (s.equalsIgnoreCase(termToCheck)) {
count++;
}
}
return count;
}
然后我在下面的代码中使用它来计算String[] words
for(String word:words){
int freq = tfCalculator(words, word);
System.out.println(word + "|" + freq);
mm+=word + "|" + freq+"\n";
}
我所遇到的问题是,这里的重复词是例如结果:
所以有人可以帮我删除重复的单词并得到如下结果:
非常感谢!
答案 0 :(得分:2)
Java 8解决方案
words = Arrays.stream(words).distinct().toArray(String[]::new);
distinct
方法删除重复项。 words
被替换为没有重复的新数组
答案 1 :(得分:0)
您可以使用HashSet
,这应该解决重复问题:
words = new HashSet<String>(Arrays.asList(words)).toArray(new String[0]);
这将获取您的数组,将其转换为List
,将其提供给HashSet<String>
的构造函数,然后将其转换回数组。
答案 2 :(得分:0)
对数组进行排序,然后您可以计算相等的相邻元素:
Arrays.sort(totalterms);
int i = 0;
while (i < totalterms.length) {
int start = i;
while (i < totalterms.length && totalterms[i].equals(totalterms[start])) {
++i;
}
System.out.println(totalterms[start] + "|" + (i - start));
}
答案 3 :(得分:0)
我想在这里你要打印数组totalterms中每个字符串的频率。我认为使用Map是一个更简单的解决方案,因为在单个遍历数组时它将存储所有字符串的频率检查以下实现。
public static void printFrequency(String[] totalterms)
{
Map frequencyMap = new HashMap<String, Integer>();
for (String string : totalterms) {
if(frequencyMap.containsKey(string))
{
Integer count = (Integer)frequencyMap.get(string);
frequencyMap.put(string, count+1);
}
else
{
frequencyMap.put(string, 1);
}
}
Set <Entry<String, Integer>> elements= frequencyMap.entrySet();
for (Entry<String, Integer> entry : elements) {
System.out.println(entry.getKey()+"|"+entry.getValue());
}
}
答案 4 :(得分:0)
分两行:
String s = "cytoskeletal|2 - network|1 - enable|1 - equal|1 - spindle|1 - cytoskeletal|2"; System.out.println(new LinkedHashSet(Arrays.asList(s.split("-"))).toString().replaceAll("(^\[|\]$)", "").replace(", ", "- "));
答案 5 :(得分:0)
您的代码很好,您只需要跟踪已遇到的单词。为此你可以保持一个运行集:
Set<String> prevWords = new HashSet<>();
for(String word:words){
// proceed if word is new to the set, otherwise skip
if (prevWords.add(word)) {
int freq = tfCalculator(words, word);
System.out.println(word + "|" + freq);
mm+=word + "|" + freq+"\n";
}
}