【问题标题】:How do I take a compressed file (through indexes) and re-create the original file? (Java)如何获取压缩文件(通过索引)并重新创建原始文件? (爪哇)
【发布时间】:2017-03-29 17:10:39
【问题描述】:

问题背景

我一直在开发一些代码,首先关注的是读取字符串和创建文件。其次,将字符串拆分为数组。然后获取数组中每个单词的索引,最后删除重复项并将其打印到不同的文件中。 我目前已经为此编写了代码,这里是一个链接https://pastebin.com/gqWH0x0(也有一个菜单系统),但它相当长,所以我没有在这个问题中实现它。

压缩方法是通过 hashmaps 完成的,获取数组的索引并将它们映射到相关的单词。这是一个例子:

原文:《海见海见海见》

输出:见[2, 4, 5],sea[0, 1, 3],

问题

下一阶段是将输出恢复到原始状态。我目前对 java 比较陌生,所以我不知道所需的技术。代码应该能够获取输出文件(如上所示)并将其放回原始文件。

我目前的想法是您只需重写此哈希图(如下)。我这样想对吗?我想我应该先检查堆栈溢出!

Map<String, Set<Integer>> seaMap = new HashMap<>(); //new hashmap
                    for (int seaInt = 0; seaInt < sealist.length; seaInt++) {
                        if (seaMap.keySet().contains(sealist[seaInt])) {
                            Set<Integer> index = seaMap.get(sealist[seaInt]);
                            index.add(seaInt);
                        } else {
                            Set<Integer> index = new HashSet<>();
                            index.add(seaInt);
                            seaMap.put(sealist[seaInt], index);
                        }                
                    }
                    System.out.print("Compressed: ");
                    seaMap.forEach((seawords, seavalues) -> System.out.print(seawords + seavalues + ","));
                    System.out.println("\n");

如果有人有任何好的想法/答案,请告诉我,我真的很渴望解决方案!

链接到当前代码:https://pastebin.com/gqWH0x0K

【问题讨论】:

    标签: java hashmap compression hashtable


    【解决方案1】:

    首先,您必须使用您的示例将带有索引的单词与压缩行分开:

    "see[2, 4, 5],sea[0, 1, 3],"
    

    获取以下字符串:

    "see[2, 4, 5]" and "sea[0, 1, 3]"
    

    对于每个您必须阅读的索引,例如首先:

    2, 4 and 5
    

    现在只需在给定索引处的 ArrayList(或数组)中写入单词。

    对于前两个步骤,您可以使用正则表达式来查找每个单词和索引列表。然后使用 String.split 和 Integer.parseInt 获取所有索引。

    Pattern pattern = Pattern.compile("(.*?)\\[(.*?)\\],");
    String line = "see[2, 4, 5],sea[0, 1, 3],";
    Matcher matcher = pattern.matcher(line);
    while (matcher.find()) {
        String word = matcher.group(1);
        String[] indexes = matcher.group(2).split(", ");
        for (String str : indexes) {
            int index = Integer.parseInt(str);
    

    现在只需检查结果列表是否足够大并将单词设置在找到的索引处。

    【讨论】:

    • 你知道我怎样才能让索引和单词放在一起吗?
    • “在给定索引处将单词写入 ArrayList(或数组)”和“只需检查结果列表是否足够大并将单词设置在找到的索引处”之后只需加入字符串result[0] + result[1] + ...(显然是在循环中或使用流)——我只是想给你主要的想法,不要指望我做你的工作,我自己就够了!
    猜你喜欢
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 2014-06-20
    • 2019-02-24
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多