2017-02-09 240 views
1

我需要修復此程序,以便從解壓縮的文件中刪除標點符號。例如,當文件原始文本被解壓縮時,單詞和標點符號之間有空格。在python中壓縮和解壓縮文本文件

例如:cheese ,

應該返回cheese,

def RemoveSpace(ln): #subroutine used to remove the spaces after the punctuation 
    line = ""  
    line2 = "" 
    puncpst = [] 
    for g in range(1, len(line)): 
     if line[g] == "." or line[g] == "," or line[g] == "!" or line[g] == "?": 
      puncpst.append(g) #get the positions of punctuation marks in a list 
    for b in range(len(line)): 
     if b + 1 not in puncpst: 
     line2 = line2 + line[b] 
    return line2 
+0

EF RemoveSpace(LN):所使用的標點符號 行之後以刪除空格#subroutine = 「」 LINE2 =」 「 puncpst = [] g範圍內(1,len(行)): if line [g] ==」。「或行[g] ==「,」或行[g] ==「!」或線[g] ==「?」: puncpst.append(g)#如果b + 1不在puncpst中,請爲列中的b獲取標點符號列表 中的位置: : line2 = line2 + line [b] return line2 – Manal

+0

您應該確保您的程序格式正確。 Python對此非常關注。除此之外,我沒有看到你的程序如何檢查標點符號之前是否有空格。 – quamrana

回答

0

的原因碼不起作用是if語句後的壓痕。請更正如下壓痕:

if b+1 not in puncpst: 
    line2 = line2+line[b] 

另一種方法來處理它是直接替換字符串中的空間:

line.replace(" .",".") 
line.replace(" ,",",") 
0

這聽起來像你的程序應該是這樣的:

def RemoveSpace(line): 
    puncpst = [] 
    for g in range(1, len(line)): 
     if line[g] == "." or line[g] == "," or line[g] == "!" or line[g] == "?": 
      puncpst.append(g) #get the positions of punctuation marks in a list 
    ret = "" 
    for b in range(len(line)): 
     if b + 1 not in puncpst: 
      ret += line[b] 
    return ret 

您原來的def RemoveSpace(ln):其中ln未被使用

的改進版本,帶頭從@ v.coder,可能是這樣的:

def RemoveSpace2(line): 
    punctuation = ['.', ',', '!', '?'] 
    for p in punctuation: 
     original = ' ' + p 
     line = line.replace(original, p) 
    return line