在给出职位后压缩用户的句子

时间:2017-01-18 16:07:13

标签: python compression python-3.4 code-completion

我在下面完成了这段代码,并对压缩部分有所帮助。代码不起作用,我不明白如何解决它。在我的课堂上,我们仍然是初学者,所以我不太好。当它向用户询问一个句子时,为什么它会说明为b' _'而不是请输入一个句子?

import gzip
File = open('Users Sentence.txt', 'w') 
Sentence = input(b"Please input a sentence ")                                                                
print (Sentence)                                                                                            
varNameIn = Sentence.encode('utf8')
Lower = Sentence.lower()                                                                                    
Splitsentence = Lower.split()                                                                                                                                                              

Userfile = File.write(Sentence)                                                                             
varNameIn = Splitsentence 
varNameOut = gzip.compress(varNameIn)
print(varNameOut)

varNameDecon = gzip.decompress(varNameOut)
print(varNameDecon.decode('utf-8'))

positions = {Splitsentence:index for index, Splitsentence in reversed(list(enumerate(Splitsentence, 1)))}   
fileposition = (' '.join(str(positions.get(word)) for word in Splitsentence))
print (fileposition)                                                                                        
Userfile = File.write(fileposition)                                                                         
File.close()                                                                                                

它给了我这个错误信息,我不明白:

Traceback (most recent call last):
  File "\\USER-PC\Users\user\Documents\homework\CW Computing\2.py", line 11, in <module>
    varNameOut = gzip.compress(varNameIn)
  File "C:\Python34\lib\gzip.py", line 624, in compress
    f.write(data)
  File "C:\Python34\lib\gzip.py", line 343, in write
    self.crc = zlib.crc32(data, self.crc) & 0xffffffff
TypeError: 'list' does not support the buffer interface

感谢。

1 个答案:

答案 0 :(得分:1)

您的代码带有我的注释:

Sentence = input(b"Please input a sentence ") # Sentence is type str
print (Sentence)
varNameIn = Sentence.encode('utf8') # not used
Lower = Sentence.lower() # Lower is type str
Splitsentence = Lower.split() Splitsentence is a list of str objects
Userfile = File.write(Sentence) # Userfile = number of chars written (??)
varNameIn = Splitsentence # varNameIn is a list of str objects
varNameOut = gzip.compress(varNameIn) # attempting to compress a list

您需要重新考虑您希望进行数据压缩的内容/原因......