удалите символы с помощью регулярных выражений, а затем верните их обратно - PullRequest
1 голос
/ 19 марта 2020

Я пытаюсь удалить пунктуацию на строке с помощью регулярного выражения, затем выполнить некоторый анализ и затем вернуть пунктуацию туда, где она была после анализа. Я удалил его, но не уверен, как его вернуть после внесения изменений?

import re
s = "I want to remove all the punctuation, and then put it, back where it was."
s = re.sub(r'[^\w\s]','',s)

lst = s.split()
# now i  change the list
# how to put the symbols back after i change the list?

Ответы [ 4 ]

0 голосов
/ 19 марта 2020

Вы можете использовать re.sub с шаблоном, который будет сопоставлять или захватывать фрагменты пунктуации или фрагменты без пунктуации и передавать объект сопоставления вызываемому объекту, где вы можете вносить любые изменения в строки без пунктуации, в то время как просто возврат текстов пунктуации без изменений:

import re
def repl(m):
    if m.group(1):
        return m.group(1).upper()
    else:
        return m.group()

s = "I want to remove all the punctuation, and then put it, back where it was."
s = re.sub(r'([\w\s]+)|[^\w\s]+', repl, s)
print(s) # => I WANT TO REMOVE ALL THE PUNCTUATION, AND THEN PUT IT, BACK WHERE IT WAS.

См. демо Python и демо regex .

0 голосов
/ 19 марта 2020

Вы просто хотите убедиться, что вы не изменяете исходную строку, которая является s. Чтобы сделать это возможным, присвойте результат re.sub новой переменной:

modified_s = re.sub(r'[^\w\s]','',s)

Это не изменяет исходный s. Вы можете сделать весь свой анализ на modified_s, а когда вам нужен оригинал, получите его от s.

import re

s = "I want to remove all the punctuation, and then put it, back where it was."
modified_s = re.sub(r'[^\w\s]','',s)  # new object

lst = modified_s.split()              # perform operations on the new object.

print(s)                              # this is still the original object.
0 голосов
/ 19 марта 2020

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, чтобы я мог снова превратить его в строку с изменениями и исходными символами.

У вас есть два простых варианта:

  1. с использованием str.replace. во-первых, не преобразовывать его в строку.
  2. конвертировать, включая знаки препинания.

решение 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.
0 голосов
/ 19 марта 2020

Вместо этого вы можете создать временную строку и попробовать это ниже:

    input_string = "I want to remove all the punctuation, and then put it, back where it was."
    s = input_string
    s = re.sub(r'[^\w\s]', '', s)

    lst = s.split()

    print(input_string)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...