在python中压缩和解压缩文本文件

时间:2017-02-09 15:59:53

标签: 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 

2 个答案:

答案 0 :(得分:0)

代码不起作用的原因是if语句后的缩进。请更正下面的缩进:

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

另一种处理方法是直接替换字符串中的空格:

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

答案 1 :(得分: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