压缩字符串和列表:类型错误

Compression Strings & List: Type Error

在尝试了很多方法后,我一直 运行 遇到很多类型错误。这是我现在拥有的代码,我需要能够将其压缩到一个文件中。

import zlib
sentence = input("Enter the text you want to compress: ")
listSentence = sentence.split(" ")
d = {}
i = 0
values = []
for i, word in enumerate(sentence.split(" ")):
    if not word in d:
        d[word] = (i+1)
    values += [d[word]]
coms = zlib.compress(sentence.encode('utf-8'))
comv = zlib.compress(values.encode('utf-8'))
with open("listofwords.txt", "wb") as myfile:
    myfile.write(coms)
    myfile.write(comv)

我一直收到类型错误: Type error: List does not support the buffer interface

如有任何帮助,我们将不胜感激!

也许这就是你想要的

import zlib
sentence = input("Enter the text you want to compress: ")
listSentence = sentence.split()
d = dict()
values = [d.setdefault(w,sentence.find(w)) for w in listSentence]
print(values)
coms = zlib.compress(sentence.encode('utf-8'))
comv = zlib.compress(bytes(values))
with open("listofwords.txt", "wb") as myfile:
    myfile.write(coms)
    myfile.write(comv)

产生,例如

Enter the text you want to compress: hello world hello
[0, 6, 0]

和一个包含压缩句子的文件,后跟每个单词在句子中第一次出现的位置的压缩列表,即

mbb@dev:~/SO/py$ cat listofwords.txt 
x��H���W(�/�IQ��; �x�c`c

注意:名为 d 的词典用于缓存单词在句子中的位置,以避免在句子中扫描已经遇到的单词。

注2:我个人会给输出文件另一个后缀,例如.bin