Замена слов и словесных строк в python - PullRequest
0 голосов
/ 26 октября 2019

В Python 3 для замены строк, как мне сделать все комбинации: с учетом регистра / без учета регистра, словосочетания / без слов и полной замены / включая исходный текст?

1 Ответ

0 голосов
/ 26 октября 2019

Это можно сделать с помощью регулярных выражений из Python. Примеры для Python 3:

import re
test_string = 'Will william unwillingly goodwill (WiLl)?'

#case sensitive find and replace
to_match = re.compile('will') 
new_string = re.sub(to_match, 'what', test_string)
print('Example 1: ' + new_string)

#case insensitive find and replace
to_match = re.compile('will', re.IGNORECASE) 
new_string = re.sub(to_match, 'what', test_string)
print('Example 2: ' + new_string)

#word based case insensitive find and replace
to_match = re.compile(r'\bwill\b', re.IGNORECASE) 
new_string = re.sub(to_match, 'what', test_string)
print('Example 3: ' + new_string)

#word based case insensitive find and replace including original text
to_match = re.compile(r'(\bwill\b)', re.IGNORECASE) 
new_string = re.sub(to_match, r'{\1}', test_string)
print('Example 4: ' + new_string)

#start of word based find and replace
to_match = re.compile(r'\bwill', re.IGNORECASE) 
new_string = re.sub(to_match, 'what', test_string)
print('Example 5: ' + new_string)

#Case insensitive find and replace with original text, but in uppercase
def upper_replace(match):
    return '{' + match.group(1).upper()
to_match = re.compile(r'(will)\b', re.IGNORECASE) 
new_string = re.sub(to_match, upper_replace, test_string)
print('Example 6: ' + new_string)

Это выводит:

Example 1: Will whatiam unwhatingly goodwhat (WiLl)?
Example 2: what whatiam unwhatingly goodwhat (what)?
Example 3: what william unwillingly goodwill (what)?
Example 4: {Will} william unwillingly goodwill ({WiLl})?
Example 5: what whatiam unwillingly goodwill (what)?
Example 6: {WILL william unwillingly good{WILL ({WILL)?

Дайте мне знать, если необходимо охватить более простые варианты замены строки.

...