间距和图案替换

Spacing and pattern replacement

这是两部分问题:

第 1 部分

要删除多个空格,将段落拆分为一个空格。

当前代码:

import re
# Read inputfile
with open('input.txt', 'r') as file :
  inputfile = file.read()

# Replace extras spaces with single space.
#outputfile = re.sub('\s+', ' ', inputfile).strip()
outputfile = ' '.join(inputfile.split(None))

# Write outputfile
with open('output.txt', 'w') as file:
  file.write(outputfile)

第 2 部分:

删除多余的空格后;我搜索并替换模式错误。

喜欢:'['到'['

Pattern1 = re.sub(' [ ', ' [', inputfile)

这会引发错误:

引发错误,v # 无效表达式 错误:正则表达式意外结束

虽然。这有效...(例如:将连字符前后的单词连接在一起)

Pattern1 = re.sub(' - ', '-', inputfile)

在解决空格问题后,我有很多关于标点问题的情况需要处理。

我不希望模式查看先前模式结果的输出并进一步移动。

有没有更好的方法来将标点符号周围的空格剪到恰到好处。

对于第一部分,您可以将其按换行块拆分,压缩每一行,然后在换行符上重新加入,如下所示:

import re
text = "\n".join(re.sub(r"\s+", " ", line) for line in re.split("\n+", text))
print(text)

对于第二部分,您需要对 [ 进行转义,因为它是一个正则表达式元字符(用于定义字符 类),如下所示:

import re
text = re.sub("\[ ", "[", text)
text = re.sub(" ]", "]", text)
print(text)

请注意,您不需要对 ] 进行转义,因为它与 [ 不匹配,因此在这种情况下它并不特殊。

Try It Online!

或者对于第二部分,text = text.replace("[ ", "[").replace(" ]", "]") 因为您甚至不需要正则表达式。