1

«статья 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())
4

1 に答える 1