【问题标题】:Run-Length encoding gives the same number to all repeating values运行长度编码为所有重复值提供相同的数字
【发布时间】:2014-06-09 14:53:08
【问题描述】:

我正在为混合不同压缩算法的短字符串构建一个压缩器,而 RLE 就是其中之一,这就是问题所在。

我现在的脚本如下,虽然目前还很不完整:

# -*- coding: utf-8 -*-

import re

dictionary = {'hello':'\§', 'world':'\°', 'the': '\@', 'for': '\]'}
a_test_string = 'hello******** to the world****!'

def compress(string, dictionary):
    pattern = re.compile( '|'.join(dictionary.keys() )) 
    result = pattern.sub(lambda value: dictionary[value.group() ], string)

    '''
    Here I should also implement a snippet to check for characters beginning with "\" so that they won't get replaced and screw up the result.
    '''

    for character in string:
        occurrence = string.count(character*2)
        there_is_more_than_one_occurrence = occurrence > 1

        if there_is_more_than_one_occurrence:

                second_regex_pass_for_multiple_occurrences = re.sub('\*\*\*+', '/'+character+str(occurrence), result)
                result = second_regex_pass_for_multiple_occurrences

    print 'Original string:', string

    print 'Compressed string:', result

    print 'Original size:', len(string)

    print 'Compressed size:', len(result)


compress(a_test_string, dictionary)

当我运行这个函数时,我得到了这个:

Original string: hello******** to the world****!
Compressed string: \§/*6 to \@ \°/*6!
Original size: 31
Compressed size: 20

但我应该得到:

Original string: hello******** to the world****!
Compressed string: \§/*8 to \@ \°/*4!
Original size: 31
Compressed size: 20

我在这里做错了什么,我得到两个 6 作为重复字符的计数?

【问题讨论】:

  • 旁白:你的缩进看起来很奇怪,这通常是混合制表符和空格的标志。您能否检查以确保您使用的是一致的缩进(一种方法是使用-tt 运行您的脚本,例如python -tt your_program_name.py。)

标签: python compression run-length-encoding


【解决方案1】:

我不会试图准确地理解你在做什么,但一个好的调试方法是在你的 for 循环中添加一些“打印”语句,或者使用 python 调试器看看实际发生了什么。尝试自己运行其中一些调用,看看返回了什么。

我认为您的主要问题是“string.count”返回整个字符串的计数,因此当它第一次检查 2 个*s 时,它会看到所有 12 个(或技术上所有 6 个** 模式) .当 for 循环检查下一组 *s 时,它仍在检查整个字符串。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多