2016-01-20 58 views
-1

尝试了很多方法后,我经常遇到很多类型的错误。这里是我现在的代码,我需要能够压缩到一个文件。压缩字符串和列表:类型错误

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

任何援助将不胜感激!

+1

当您想要帮助发生错误时,您总是需要发布回溯。 – thebjorn

+0

好吧,就像实际的错误说的那样,'values'是一个列表,你不能编码一个列表。你想达到什么目的?请注意,在您的代码中,“值”只是从1到您句子中唯一字数的整数列表。 –

+0

@DanielRoseman值和输入都需要压缩。 – Trent

回答

1

也许这是你想要的

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] 

,并与压缩的句子,然后每个第一次出现的位置的压缩列表的文件单词中的句子,即

[email protected]:~/SO/py$ cat listofwords.txt 
x��H���W(�/�IQ��; �x�c`c 

注意:字典命名为d是否有缓存在句子中找到的单词的位置,以避免扫描已经遇到的单词的句子。注2:我会亲自给输出文件另一个后缀,例如: .bin

+0

我不认为OP需要一个计数,但第一次出现的位置。 – AChampion

+0

@AChampion好的,谢谢你的提示。更新 – Pynchia

+0

谢谢你,很好!对不起,对此不清楚! – Trent