![](/img/trans.png)
[英]Why does my len() code in python not provide the correct length of a string?
[英]Why does my string of length 1 change to length 3?
我一直在尝试制作一个压缩系统,但是我的字符串不断从长度 1 变为长度 3 长度 2:变为长度 5 长度 3:变为长度 7 长度 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 中尝试的所有内容都无法解决它。 我一直在寻找几个小时,但没有找到答案。
更新
我找到了答案。 现在我已经创建了一个新的 function 来找到制作最佳压缩系统的参数。 我已经达到了原始长度的 40%。 我还添加了一个系统来检查重复的文本,所以它会压缩得更多
就像 jasonharper 说的:
您正在为长度为 0、1 和 2 的字符的排列生成映射。2 个字符的替换实际上可能会实现一些压缩; 1 个字符的替换完全没有意义,因为长度没有减少。 而 0 字符替换是杀死你的原因,因为在你的输入中空字符串匹配的每个地方(比字符数大一个)都会被一个字符替换。 将传递给 makemap() 的范围的下限设置为 1 或 2 可能会让你更进一步jasonharper 回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.