Заменить числа в слове на символ - PullRequest
3 голосов
/ 13 мая 2019

У меня есть строка вроде:

s ="Question1: a12 is the number of a, 1b is the number of b"

Используя x = re.compile('\w+').findall(s) Я могу получить

['Question1', 'a12', 'is', 'the', 'number', 'of', 'a', '1b', 'is', 'the', 'number', 'of', 'b']

Теперь я хочу заменить число в слове, например,

  • Question1 -> Question$
  • a12, 1b -> a$, $b

Я пробовал y = [re.sub(r'\w*\d\w*', '$', x) for w in x]

но возвращает целое слово, замененное на $:

['$', '$', 'is', 'the', 'number','of', 'a', '$', 'is', 'the', 'number', 'of', 'b']

Я хочу спросить, есть ли способ заменить его правильно, и, если возможно, объединить поиск и замену в одной функции.

Ответы [ 4 ]

2 голосов
/ 13 мая 2019

Вы можете адаптировать следующий образец для удовлетворения ваших требований:

Если цифры для замены находятся только в конце слов:

import re

s = "Question1: a12 is the number of a, 1b is the number of b, 123"
x = re.compile('\w+').findall(s)
y = [re.sub(r'(?<=[a-zA-Z])\d+$', '$', w) for w in x]
print(y)

Выход:

['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '1b', 'is', 'the', 'number', 'of', 'b', '123']

В один шаг (результат в виде строки):

import re
s ="Question1: a12 is the number of a, 1b is the number of b, abc1uvf"
pat = re.compile(r'(?<=[a-zA-Z])\d+(?=\W)')
print(re.sub(pat, "$", s))

Выход:

Question$: a$ is the number of a, 1b is the number of b, abc1uvf

Если числа могут быть расположены в любом месте слова:

import re

s = "Question1: a12 is the number of a, 1b is the number of b, 123"
x = re.compile('\w+').findall(s)
y = [re.sub(r'\d+', '$', w) for w in x]
print(y)

Выход:

['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '$b', 'is', 'the', 'number', 'of', 'b', '$']

Обратите внимание, что 123 заменяется на $, если это не то, что вы хотите использовать:

import re

s = "Question1: a12 is the number of a, 1b is the number of b, 123"
x = re.compile('\w+').findall(s)
y = [re.sub(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])', '$', w) for w in x]
print(y)

Выход:

['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '$b', 'is', 'the', 'number', 'of', 'b', '123']

За один шаг:

import re

s = "Question1: a12 is the number of a, 1b is the number of b, 123"
y = re.sub(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])', '$', s)
print(y)
1 голос
/ 13 мая 2019

Попробуйте это:

import re
x = ['Question1', 'a12', 'is', 'the', 'number', 'of', 'a', '1b', 'is', 'the', 'number', 'of', 'b']
y = [re.sub(r'\d+', '$', w) for w in x]
print(y)

выход:

['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '$b', 'is', 'the', 'number', 'of', 'b']
1 голос
/ 13 мая 2019

Объяснение:

  • Первый аргумент re.sub - это цифра, которую вы хотите заменить.

    \d+находит цифры, + в которых обозначает один или несколько вхождений цифры.

  • Второй аргумент требует замены шаблона.В этом случае его '$'.

  • Третий аргумент принимает входную строку.

Это работает так, как вы хотите:

import re
s ="Question1: a12 is the number of a, 1b is the number of b"
print(re.sub('\d+', '$', s))

Выход:

Question$: a$ is the number of a, $b is the number of b
1 голос
/ 13 мая 2019

Попробуйте это:

import re
s ="Question1: a12 is the number of a, 1b is the number of b"
pat = re.compile("[0-9]+")
print(re.sub(pat, "$", s))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...