Замена символов в списке на основе условий - PullRequest
0 голосов
/ 19 февраля 2019

Я пытаюсь заменить символы в моем списке на основе некоторых условий.

tmp = ['T', 'h', 'e', '/', ' * ', 's', 'k', 'y', ' * ', 'i', 's', '/', '/', 'b', 'l', 'u', 'e']
tmp_string = "".join(tmp)
result = re.sub(r'[\*|/]{2}', ' ', tmp_string)
result = result.title().replace('*', ' ').replace('/', ' ').replace('  ', ' ')

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

  • Ожидаемое: небо голубое
  • Мой вывод: голубое небо

Я не хочу, чтобы 'i' of 'is' получалокапитализируются.

Ответы [ 3 ]

0 голосов
/ 19 февраля 2019

Проблема с title(), которая будет использовать заглавные буквы для каждого первого символа строки.IUCC простой пример поможет вам.Используйте title() с условием

' '.join([i.title() if i not in ['is','and'] else i for i in 'the sky is blue'.split()])
0 голосов
/ 19 февраля 2019

попробуйте

import re
tmp=['T', 'h', 'e', '/', ' * ', 's', 'k', 'y', ' * ', 'i', 's', '/', '/', 'b', 'l', 'u', 'e']

misc_words = ('is', 'the')

tmp_string = "".join(tmp)
result = re.sub(r'[\*|/]', ' ', tmp_string)
result = re.sub(r' +', ' ', result) # replace one or more consecutive spaces with a single space
#result = result.title().replace('*', ' ').replace('/', ' ').replace('  ', ' ') # this is done by fixng the first regex
words = result.split()
new_words = []
for word in words:
    if word not in misc_words:
        new_words.append(word[0].upper() + word[1:])
    else:
        new_words.append(word)

print(new_words)
0 голосов
/ 19 февраля 2019

Вы можете использовать генератор с троичным выражением, чтобы проверить, буквенно-цифровые символы или нет:

import re

l = ['T', 'h', 'e', '/', ' * ', 's', 'k', 'y', ' * ', 'i', 's', '/', '/', 'b', 'l', 'u', 'e']

tmp = "".join(char if char.isalpha() else ' ' for char in l)

# This will put spaces where the * and / are

# then use regex to compress the spaces

mystr = re.sub('\s{2,}', ' ', tmp)

print(mystr)

Выходы: небо голубое

Затем, чтобы получить желаемый результат:

chars = []
not_capitalize = set(['is', 'and']) # you can put other words in here that you don't want to capitalize

# split will create an array of words split on spaces
for char in mystr.split():
    if char in not_capitalize:
        chars.append(char)
        continue

    # Separate the first letter from the rest of the word
    first_letter, rest = char[0], char[1:]

    # stitch the uppercase first_letter with the rest of the word together
    chars.append("%s%s"% (first_letter.upper(), rest))

# join and print
print(' '.join(chars))

# Gives The Sky is Blue
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...