如何压缩文本文件

时间:2017-05-08 03:39:18

标签: python

无论如何都要压缩此代码中使用的文本。我很感激你的帮助 Heya,无论如何都要压缩此代码中使用的文本。我很感激你的帮助。

$(document).ready(function(){
  // your code
});

2 个答案:

答案 0 :(得分:1)

问题有点模糊......如果你的意思是数据压缩,那么你可以使用二进制变换。

In [1]: import codecs

In [2]: example = 'abcdefg'*100

In [3]: compressed = codecs.encode(example.encode(), 'zlib')

In [4]: compressed
Out[4]: b'x\x9cKLJNIMKO\x1c\xa5F\xa9\xa1F\x01\x00m\x8e\x11\x80'

In [5]: decompressed = codecs.decode(compressed, 'zlib')

In [6]: decompressed
Out[6]: b'abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg'

查看docs编解码器,底部是为二进制转换提供的内置编解码器。

但是,如果你的意思是压缩来表达你希望减少代码行,那么当代码的意图有点模糊时,我会想象你想要过滤掉重复的单词,同时可能保留单词的顺序... < / p>

没有订单:

' '.join(set(sentence.split()))

订购:

seen = set()
words = sentence.split()
new = []
for word in words:
    if word not in seen:
        seen.add(word)
        new.append(word)
unique_ordered = ' '.join(new)

答案 1 :(得分:0)

您好像在问是否可以减少您拥有的代码行。这是我的尝试:

 with open("Test.txt", "r") as file:
     Sentence = file.read().split(" ")
 ListSentence, uniquewords = [], []
 print(Sentence)
 for x in s:
     if x not in uniquewords:
         uniquewords.append(x)
     ListSentence.append(uniquewords.index(x)) # you do this every loop anyway
 print(ListSentence)

 recreated = ""
 for position in ListSentence:
    recreated += uniquewords[position] + " "
 print(uniquewords)
 print(recreated)