2017-04-23 74 views
0

我已經創建了一個模塊,應根據字符重複的次數使用特定替換來刪除重複字符。例如,如果使用「α」重複4次,將「一」和「¤」這兩個值都等於1個字節。我遇到的問題是當文件尺寸變至超過30KB左右,當我完成運行模塊它有一些如何字節大小增加。我已經嘗試了一些字計數程序,顯然它增加了更多的字符我只是一直沒能解決我的代碼。我嘗試了幾種方法,希望得到一些關於如何添加字節的幫助或想法。Python:刪除重複字符,但字節中的文件大小仍在增加

from itertools import groupby 

with open("LICENSE.txt","r", encoding='utf-8') as rf, open('TESTINGOnline.txt','w', encoding='utf-8') as wf: 
s = rf.read() 
ret = '' 
for k, v in groupby(s): 
    x = 'a' 
    chunk = list(v) 
    cnt = len(chunk) 

    if k == x and cnt <= 1: 
     el = 'ª'.rstrip('\n') 
    elif k == x and cnt == 2: 
     el = '¨'.rstrip('\n') 
    elif k == x and cnt == 3: 
     el = '­'.rstrip('\n') 
    elif k == x and cnt == 4: 
     el = '¤'.rstrip('\n') 
    elif k == x and cnt == 5: 
     el = '¥'.rstrip('\n') 

    else: 
     el = ''.join(chunk).rstrip('\n') 
    ret += el 
wf.write(ret.rstrip('\n')) 

回答

0

怎麼弄,文件大小增長的解釋很簡單:

print(len(bytes("¥ª¤¨", 'utf-8'))) 

8 

你假設你用另一個字節替換一個字節錯誤。您正在使用一個UTF-8字符替換一個UTF-8代碼爲一個字節長的UTF-8字符,而UTF-8代碼爲兩個字節長。

無需修復您的代碼 - juxt修正你的假設:)

也許檢查出我的回答以下兩個問題可以幫助你更好地瞭解怎樣的一個人物和什麼是一個字節?

Converting UTF-8 (in literal) to Umlaute

In Python 3, how can I convert ascii to string, *without encoding/decoding*

+0

你先生是天才,拿出了UTF-8編碼和繁榮字節下樓,戴的帽子。 – LetsChangeTheWorld