Как удалить символы из начала и конца строки, но не из середины? - PullRequest
1 голос
/ 19 апреля 2020

Меня попросили написать функцию, которая возвращает строку со всеми указанными пунктуацией в начале и конце каждого удаленного слова , не затрагивая те, которые находятся внутри слов , такие как ban, ana. Как я мог сделать это, используя петли?

    def beautify_sentence(sentence, punctuation):
        for element in punctuation:
            sentence = sentence.replace(element, "")
        return sentence

    print(beautify_sentence("?hello !mango! ...and., ban,ana.. yum?? apple!", "!?.,"))

    # correct answer = hello mango and ban,ana yum apple
    # my answer = hello mango and banana yum apple

Ответы [ 4 ]

1 голос
/ 19 апреля 2020

Стоит отметить, что python имеет полосы, полоски и полоски. lstrip и rstrip удаляют символы для начала и конца строки.

Используя аналогичный код, который у вас есть.

sentance="?hello !mango! ...and., ban,ana.. yum?? apple!"
punctuations="!?.,"

def beautify_sentence(sentence, punctuation):
    words = []

    for word in sentance.split(' '):
        words.append(word.lstrip(punctuations).rstrip(punctuations))

    return " ".join(words)

print(beautify_sentence(sentance, punctuations))

Но, как уже упоминалось, полоса будет удалена спереди и сзади.

sentance="?hello !mango! ...and., ban,ana.. yum?? apple!"
punctuations="!?.,"

def beautify_sentence(sentence, punctuation):
    words = []

    for word in sentance.split(' '):
        words.append(word.strip(punctuations))

    return " ".join(words)

print(beautify_sentence(sentance, punctuations))
1 голос
/ 19 апреля 2020

Здесь вы можете использовать str.strip для ваших отдельных слов:

def beautify_sentence(sentence, punctuation):
    return ' '.join([x.strip(punctuation) for x in sentence.split()])

>>> beautify_sentence("?hello !mango! ...and., ban,ana.. yum?? apple!", "!?.,")
hello mango and ban,ana yum apple
0 голосов
/ 19 апреля 2020

Немного дольше, но я надеюсь, что вы легко поймете алгоритм из этого пошагового подхода.

def beautify(sentence, punctuation):
    sen = sentence
    punc = punctuation

    words = sen.split(" ")  # splits into a list of words

    ret = []  # return the processed words

    for word in words:  # process each word one by one
        noPuncInTheStart = False
        noPuncInTheEnd = False

        # don't really mind this. See the break statements! 
        while (True):

            # Check the length of the word to prevent error
            # And if there is any punctuation in the beginning
            if (len(word) > 0 and not noPuncInTheStart):
                if (word[0] in punc):  # if the word started by punc
                    word = word[1:]  # remove the first character
                else:  # there is no any punctuation anymore
                    noPuncInTheStart = True
            else:
                # the word is no longger exists :)
                # in case the word is all punctuation, no letters, etc
                break

            if (len(word) > 0 and not noPuncInTheEnd):
                if (word[-1] in punc):  # check if the end is a punc
                    word = word[:-1]  # remove the end of the character
                else: 
                    noPuncInTheEnd = True
            else:
                break

            if (noPuncInTheStart and noPuncInTheEnd):
                # there's no longger punc, neither in the beginning
                # nor the end
                break  

        ret.append(word)  # add the processed word to the `ret` list
    ret = " ".join(ret)  # join the `ret` list into sentence
    return ret 
0 голосов
/ 19 апреля 2020

Я думаю, что это учебная задача. Итак, я делюсь другим подходом для решения этой проблемы.

Альтернативный подход

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

def beautify_sentence(sentence, punctuation):
    beautiful_sentence = ""
    for i in range(len(sentence)):
        if sentence[i] in punctuation:
            # remove punctuation at start and end of a sentence
            if i == 0 or i == len(sentence)-1:
                continue
            # remove punctuation which are not in middle of a word
            if not sentence[i-1].isalpha() or not sentence[i+1].isalpha():
                continue
        beautiful_sentence += sentence[i]
    return beautiful_sentence


if __name__ == "__main__":
    test_sentence = "?hello !mango! ...and., ban,ana.. yum?? apple!"
    test_punctuations = "!?.,"
    expected_sentence = "hello mango and ban,ana yum apple"
    sentence = beautify_sentence(test_sentence, test_punctuations)
    assert sentence == expected_sentence, (expected_sentence, sentence)

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

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