Это не очень аккуратно, но это дает ожидаемый результат:
import re
s = "Hi This is Manager Sam. Hello, this is Director.Tom. How is your Day Mr.Manager Sam."
words = ("Manager", "Director")
def add_spaces(string, words):
for word in words:
# pattern to match any non-space char before the word
patt1 = re.compile('\S{}'.format(word))
matches = re.findall(patt1, string)
for match in matches:
non_space_char = match[0]
string = string.replace(match, '{} {}'.format(non_space_char, word))
# pattern to match any non-space char after the word
patt2 = re.compile('{}\S'.format(word))
matches = re.findall(patt2, string)
for match in matches:
non_space_char = match[-1]
string = string.replace(match, '{} {}'.format(word, non_space_char))
return string
print(add_spaces(s, words))
Вывод:
'Hi This is Manager Sam. Hello, this is Director .Tom. How is your Day Mr. Manager Sam.'
Обратите внимание, что '\ S' - это символ регулярного выражения, соответствующий любому непробельному пространству.
Редактировать: вероятно, есть более аккуратный способ сделать это с re.sub
...