我需要用不间断空格替换«статья 1»、«статьи 2»等中所有出现的正常空格。下面的结构工作正常:
re.sub('(стат.{0,4}) (\d+)', r'\1 \2', text) # 'r' in repl is important, otherwise the word is not replaced correctly, at least for texts in Russian.
但是,我不想重复使用re.sub
«статья»,然后是«пункт»,然后是月份名称,我想要一本带有正则表达式和替换的字典。这是我的代码,但它没有按预期工作:'статья 1 статьи 2'
应该如下所示'статья(non-breaking space here)1 статьи(non-breaking space here)2'
:
import re
text = 'статья 1 статьи 2'
dic = {'(cтат.{0,4}) (\d+)' : r'\1 \2'}
def replace():
global text
final_text = ''
for i in dic:
new_text = re.sub(str(i), str(dic[i]), text)
text = new_text
return text
print (replace())