gpt4 book ai didi

Java hashmap 到矩阵的转换

转载 作者:行者123 更新时间:2023-12-02 11:38:10 28 4
gpt4 key购买 nike

我启动了一个 HashMap 和一个嵌套 HashMap 来存储术语、其出现次数和频率。

for (i = 1; i < lineTokens.length; i += 2) 
{
if (i + 1 >= lineTokens.length) continue;
String fileName = lineTokens[i];
int frequency = Integer.parseInt(lineTokens[i + 1]);
postingList2.put(fileName,frequency);
//System.out.println(postingList2);
}
postingList.put(topic, postingList2);

它给我输出:{cancel={WET4793.txt=16, WET5590.txt=53}, unavailable={WET4291.txt=10}, station info={WET2266.txt=32}, advocacyprogram={ WET2776.txt=32},无评分登录={WET5376.txt=76},我试图用矩阵来表示所有的事情。但我无法将不包含特定术语的文件设置为 0。就像:

row-> term
column -> document
mat[row][column]= frequency of occurances of terms in the document.

我已经使用 pandas dataframe 在 python 中轻松完成了它。

最佳答案

给定您的初始 HashMap,转换为矩阵需要三个步骤

  1. 为每个主题创建唯一的索引 ID(0、1 ..)
  2. 为每个文档创建唯一的索引 ID(0、1、..)
  3. 使用上述索引填充矩阵

此解决方案将使用 map 查找(键为发布/文档)以提高效率。过账/文件的顺序可以控制;这里没有尝试创建特定订单。

第 1 步:为帖子创建唯一 ID 并创建查找 map

Map<String, Integer> topicIndex = new HashMap<>();
List<String> topicList = new ArrayList<>(); // topicList is used to print the matrix
int index = 0;
for (String topic : postingList.keySet()) {
if (!topicIndex.containsKey(topic)) {
topicIndex.put(topic, index++);
topicList.add(topic);
}
}

该 map 的结果是(所有术语现在都有一个唯一的 ID):

Topics: {cancel=0, unavailable=1, station info=2, advocacy program=3, no ratingslogin=4}

第 2 步:为文档创建唯一 ID 并创建查找映射

index = 0;
Map<String, Integer> documentIndex = new HashMap<>();
for (String topic : postingList.keySet()) {
for (String document : postingList.get(topic).keySet()) {
if (!documentIndex.containsKey(document))
documentIndex.put(document, index++);
}
}

该映射的结果是(所有文档现在都有一个唯一的 ID):

Documents: {WET4793.txt=0, WET4291.txt=2, WET2266.txt=3, WET2776.txt=4, WET5376.txt=5, WET5590.txt=1}

第 3 步:创建并填充矩阵

int[][] mat = new int[topicIndex.size()][documentIndex.size()];
for (String topic : postingList.keySet()) {
for (String document : postingList.get(topic).keySet()) {
mat[topicIndex.get(topic)][documentIndex.get(document)] = postingList.get(topic).get(document);
}
}

结果:矩阵现在如下所示:

cancel          16 53  0  0  0  0 
unavailable 0 0 10 0 0 0
station info 0 0 0 32 0 0
advocacy program 0 0 0 0 32 0
no ratingslogin 0 0 0 0 0 76

编辑:循环打印矩阵

    for (int row = 0; row < topicIndex.size(); row++) {
System.out.printf("%-16s", topicList.get(row));
for (int col = 0; col < documentIndex.size(); col++) {
System.out.printf("%2d ", mat[row][col]);
}
System.out.println();
}

关于Java hashmap 到矩阵的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48774871/

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