我想通过使用正则表达式查找字符串中的拼写错误并在匹配的表达式之间插入空格字符来取消连接它们。
我尝试了类似问题的解决方案...但它对我不起作用 -( Insert space between characters regex );解决方案-在 re.sub 中使用替换字符串作为 '\1\2' 。
import re
corpus = '''
This is my corpus1a.I am looking to convert it into a 2corpus 2b.
'''
clean = re.compile('\.[^(\d,\s)]')
corpus = re.sub(clean,' ', corpus)
clean2 = re.compile('\d+[^(\d,\s,\.)]')
corpus = re.sub(clean2,'\1 \2', corpus)
预期输出:
This is my corpus 1 a. I am looking to convert it into a 2 corpus 2 b.
最佳答案
您需要将捕获组括号放在与要复制到结果的每个字符串相匹配的模式周围。
也无需在 \d
之后使用 +
。您只需匹配号码的最后一位数字即可。
clean = re.compile(r'(\d)([^\d,\s])')
corpus = re.sub(clean, r'\1 \2', corpus)
关于python - 在正则表达式匹配之间插入空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56944944/