gpt4 book ai didi

java - 将多集计数转换为列表 Java

转载 作者:行者123 更新时间:2023-11-30 08:54:57 26 4
gpt4 key购买 nike

有什么方法可以将 Multiset 中的计数提取到列表中吗?

String[] data = loadStrings("data/data.txt"); 

Multiset<String> myMultiset = ImmutableMultiset.copyOf(data);

for (String word : Multisets.copyHighestCountFirst(myMultiset).elementSet()) {
System.out.println(word + ": " + myMultiset.count(word));
// ...
}

就目前而言,我可以将最常出现的单词输出到 Processing 中的控制台。我想知道是否有可能将相应的单词及其计数添加到数组或列表中。我试过这样:

for (String word : Multisets.copyHighestCountFirst(myMultiset).elementSet()) {
float a[] = myMultiset.count(word);
}

但只收到错误,指出我无法将 int 转换为 float[]

这可能吗?我做错了吗?我以前从未使用过 Multiset,所以任何帮助都会非常有用

更新:我用它来获取最高计数的副本,但无法将其转换为列表。

Multiset<String> sortedList = Multisets.copyHighestCountFirst(myMultiset);

最佳答案

请参阅Multiset.entrySet() docs :

Returns a view of the contents of this multiset, grouped into Multiset.Entry instances, each providing an element of the multiset and the count of that element.

因此,为了获得前 5 个最常发生的 owrd,我将遍历 entrySet():

ImmutableMultiset<String> top = Multisets.copyHighestCountFirst(myMultiset);

Iterator<Multiset.Entry<String>> it = top.entrySet().iterator();

for (int i = 0; (i < 5) && it.hasNext(); i++) {
Multiset.Entry<String> entry = it.next();

String word = entry.getElement();
int count = entry.getCount();

// do something fancy with word and count...
}

我假设您需要显示前 5 个最常出现的词及其出现频率。如果您只需要单词,只需使用 asList()方法:

ImmutableMultiset<String> top = Multisets.copyHighestCountFirst(myMultiset);

ImmutableList<String> list = top.asList();

并迭代 list 以获取前 5 个元素。

关于java - 将多集计数转换为列表 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29269408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com