gpt4 book ai didi

java - 将数据从 List 传输到二维数组

转载 作者:行者123 更新时间:2023-12-01 10:31:53 25 4
gpt4 key购买 nike

我有一个 Java 代码,可以从包含多个句子的字符串中提取一个唯一的单词,并计算每个句子中该单词的出现次数。

这是用于实现该目的的 Java 编码。或者,您也可以尝试 here .

import java.util.*;

class Main {
public static void main(String[] args) {
String someText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

List<List<String>> sort = new ArrayList<>();
Map<String, ArrayList<Integer>> res = new HashMap<>();

for (String sentence : someText.split("[.?!]\\s*"))
{
sort.add(Arrays.asList(sentence.split("[ ,;:]+"))); //put each sentences in list
}

int sentenceCount = sort.size();
for (List<String> sentence: sort) {
sentence.stream().forEach(s -> res.put(s, new ArrayList<Integer>(Collections.nCopies(sentenceCount, 0))));
}
int index = 0;
for (List<String> sentence: sort) {
for (String s : sentence) {
res.get(s).set(index, res.get(s).get(index) + 1);
}
index++;
}
System.out.println(res);
}
}

代码的输出是这样的:

{standard=[0, 1, 0, 0], but=[0, 0, 1, 0], ..... }

这意味着“标准”一词在句子 1 中没有出现,在句子 2 中出现 1 次,在句子 3 和 4 中没有出现。

但是,数据位于列表内。如何将数据转换为二维矩阵的形式,使其变得有点像这样:

    double[][] multi = new double[][]{
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 } } //data stored in a 2D array named multi

感谢对此的帮助。谢谢。

最佳答案

循环内循环应该可以。此代码假设每行具有相同数量的元素(它们应该如此,因为每个单词可能有相同数量的句子)。我添加了一个键的 ArrayList,以便您稍后可以引用它们以了解矩阵中的哪个行索引对应于给定的单词。

ArrayList<String> keys = new ArrayList<String>(res.keySet());
int rowSize = keys.size();
int colSize = res.get(keys.get(0)).size();
double [][] multi = new double[rowSize][colSize];
for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {
String key = keys.get(rowIndex);
List<Integer> row = res.get(key);
for (int colIndex = 0; colIndex < colSize; colIndex++) {
multi[rowIndex][colIndex] = row.get(colIndex);
}
}

我将数组加倍,因为这就是问题中的内容,但似乎整数更合适。

对此答案的先前版本表示歉意;我正在查看您试图聚合的错误对象。

关于java - 将数据从 List 传输到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35043475/

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