Home > Back-end >  Preventing removal of linebreaks
Preventing removal of linebreaks

Time:07-04

I have a function that replaces offensive words with a star, but in running text through this, it strips out linebreaks. Any thoughts on how to prevent this?

def replace_words(text, exclude_list):
    words = text.split()
    for i in range(len(words)):
        if words[i].lower() in exclude_list:
            
            words[i] = "*"
    return ' '.join(words)

CodePudding user response:

Don't use .split() with no argument on the entire input string, it removes line breaks and you lose the information where you have to put them in the result string.

You could first split the input into lines and then process each line separately in the same way as you now process the whole input.

CodePudding user response:

credit to mkrieger1

def replace_words(text, exclude_list):

    paragraphs = text.split('\n')

    new_paragraph = ""

    for p in paragraphs:

        words = p.split()
        for i in range(len(words)):
            if words[i].lower() in exclude_list:
                

                words[i] = "*"
        new_p = ' '.join(words)

        new_paragraph = new_paragraph   "\n"   new_p #add line break

    return new_paragraph

CodePudding user response:

You can use \n to create a new line or .split()

  • Related