我一直想做一个压缩系统,但是我的字符串一直在变化,从长度1:变成长度3length 2:变成长度5length 3:变成长度7length 4:变成长度9等等。代码如下。
text = list(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYSZ#1234567890-_!@.+=$%:;^&*(){}[]\\|'\",<>/?`~\n\t "
)
import random
import pickle as pic
import itertools
import tools
class A:
def __init__(self):
self.wmap = {}
self.rs = []
def save(data, code):
try:
with open(code + ".pickle", "wb") as f:
pic.dump(data, f)
return True
except Exception as e:
return e
def load(code):
picklein = open(code + ".pickle", "rb")
data = pic.load(picklein)
return data
def makemap(text, num):
for i in range(num[0], num[1]):
save(a, "wmap")
print(i)
result=0
for ir in itertools.permutations(text, i):
l = ''.join(ir)
if l not in a.wmap:
while True:
result=random.randint(100, 1000000)
try:
print(chr(result))
except:
continue
if result not in a.rs and str(chr(result)) not in a.wmap and str(chr(result)) not in text and len(str(chr(result)))==1:
a.rs.append(result)
a.wmap.update({l:chr(result)})
break
a = A()
def do():
makemap(text, (0, 3))
save(a, "wmap")
print("Saved")
def compress(text):
for i in a.wmap:
x = a.wmap[i]
text = text.replace(i, x)
return text
def decompress(text):
for i in a.wmap:
x = a.wmap[i]
text = text.replace(x, i)
if text == i or text == x:
break
return text
do()
while True:
comp=compress(input("> "))
print(comp)
print("Length:",len(comp))
我认为问题出在makemap()上 但我在makemap里试了所有的方法都不能解决这个问题。我找了好几个小时,都没有找到答案。
更新
我已经找到了答案.现在我已经创建了一个新的函数,以找到使最佳压缩系统的参数。我已经实现了40%的原始长度。我还添加了一个系统,将检查重复的文本,所以它将压缩更多。
就像jasonharper说的那样。
你正在为长度为0, 1, 和2的字符组合生成映射. 2个字符的替换实际上可能会实现一些压缩;1个字符的替换完全没有意义,因为长度没有减少。而0字符替换才是要命的,因为在你的输入中,每一个空字符串匹配的地方(也就是大于字符数的地方)都会被一个字符无用地替换掉。将你传递给makemap()的范围下限设置为1或2可能会让你更进一步由 jasonharper 回答