str
является неизменным объектом в python.
s = re.sub(r'[^\w\s]','',s)
часть просто переназначает s
.
Таким образом, вы можете сохранить исходную строку с другим именем (переменной).
import re
original_s = "I want to remove all the punctuation, and then put it, back where it was."
s = re.sub(r'[^\w\s]', '', original_s)
lst = s.split()
# now i change the list
# how to put the symbols back after i change the list?
print(lst)
print(s)
print(original_s)
вывод:
['I', 'want', 'to', 'remove', 'all', 'the', 'punctuation', 'and', 'then', 'put', 'it', 'back', 'where', 'it', 'was']
I want to remove all the punctuation and then put it back where it was
I want to remove all the punctuation, and then put it, back where it was.
Добавление
Что я хочу, так это после того, как я изменю lst, чтобы вернуть все символы обратно из original_s и поместите их обратно в lst, чтобы я мог снова превратить его в строку с изменениями и исходными символами.
У вас есть два простых варианта:
- с использованием
str.replace
. во-первых, не преобразовывать его в строку. - конвертировать, включая знаки препинания.
решение 1. используя вывод str.replace
text = "PET scan is an imaging test that allows your doctor to check for diseases in your body."
acronym_dict = {
'PET': 'Positron emission tomography'
}
for acronym, word in acronym_dict.items():
text = text.replace(acronym, word)
print(text)
:
Positron emission tomography scan is an imaging test that allows your doctor to check for diseases in your body.
решение 2. lst
с пунктуацией
import re
text = "PET scan is an imaging test that allows your doctor to check for diseases in your body."
acronym_dict = {
'PET': 'Positron emission tomography'
}
lst = re.split(r'\b', text)
print(lst)
result = ''.join(
acronym_dict.get(word, word)
for word in lst
)
print(result)
вывод
['', 'PET', ' ', 'scan', ' ', 'is', ' ', 'an', ' ', 'imaging', ' ', 'test', ' ', 'that', ' ', 'allows', ' ', 'your', ' ', 'doctor', ' ', 'to', ' ', 'check', ' ', 'for', ' ', 'diseases', ' ', 'in', ' ', 'your', ' ', 'body', '.']
Positron emission tomography scan is an imaging test that allows your doctor to check for diseases in your body.