【问题标题】:Spacing and pattern replacement间距和图案替换
【发布时间】:2017-10-30 09:00:27
【问题描述】:

这是两部分的问题:

第 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)

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

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

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

【问题讨论】:

  • 当您想要做的是简单的字符串替换时,为什么要使用正则表达式查找和替换?字符[ 在正则表达式中具有含义,- 也是如此。
  • 是的,你是对的。可以使用 str 替换。但是,在速度方面,哪个更快?
  • 通常正则表达式要慢很多(在大多数编程语言中)。见:stackoverflow.com/questions/5668947/…

标签: python spacing punctuation


【解决方案1】:

对于第一部分,你可以用换行块分割它,压缩每一行,然后在换行符上加入,如下所示:

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(" ]", "]"),因为你甚至不需要正则表达式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多