虽然我在 StackOverflow 中找到了一些引用资料,但我无法编写正确的正则表达式来实现我的目标。我想从 python 中的字符串中删除特定标点符号前后的空格。
我有一个函数如下。
def modify_answers(answers):
hyp = []
for ans in answers:
# remove whitespace before - / ? . ! ;
newhyp = re.sub(r'\s([-/?.!,;](?:\s|$))', r'\1', ans)
# remove whitespace after - / $ _
newhyp = re.sub(r'', r'\1', newhyp)
hyp.append(newhyp)
return hyp
我想要实现的一些例子:
“税号是 1 - 866 - 704 - 7388。” ---> “税号是 1-866-704-7388。”
“不,鸸鹋在维多利亚州不 protected 。” ---> “不,鸸鹋在维多利亚不 protected 。”
“找到就是失去,就像构造对于 _ _ _ _ _ _ 一样。” ---> “发现就是失去,因为构造就是 ______。”
“1,0 美元等于 1,0 美元。” ---> “1,0 美元等于 1,0 美元。”
如有任何帮助,我们将不胜感激。
最佳答案
首先,定义一个执行替换的函数:
import re
def replace(x):
y, z = x.groups()
if z in '-/?.!,;':
y = y.lstrip()
if z in '-/$_':
y = y.rstrip()
return y
该函数采用匹配模式并相应地执行替换。
现在,定义您的模式。您可以预编译以提高效率。
p = re.compile(r'(\s*([-/?.,!$_])\s*)')
使用之前定义的回调在每个字符串上调用已编译的正则表达式 sub
:
cases = [
"Tax pin number is 1 - 866 - 704 - 7388 .",
"No , emu is not protected in Victoria .",
"Find is to lose as construct is to _ _ _ _ _ _ .",
"$ 1,0 is equal to $ 1,0 ."]
repl = [p.sub(replace, c) for c in cases]
print (repl)
['Tax pin number is 1-866-704-7388.', 'No, emu is not protected in Victoria.',
'Find is to lose as construct is to ______.', '$1,0 is equal to $1,0.']
关于python - 去除特定标点符号列表前后的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52227716/