r/pythonhelp • • Apr 27 '22

Python code beginner

i have a code im working on and I need help if anyone can help please,

where im defining a function:

def function(sentence, stop_words):

in which i am trying to remove all the words in the string stop_words that are present in the sentence.

I am writing this for output:

simple_sentence = stop_word_removal("This is some sentence and I know it is a long one", "and is I") print(simple_sentence)

And I need this for output:

This some sentence know it a long one

2 Upvotes

8 comments sorted by

View all comments

1

u/itachiwasright Apr 27 '22

def stop_word_removal(sentence, stop_words):

""" Returns new sentence with removed stop words. """

stop_words = stop_words.split()

s = sentence

for c in stop_words:

s = s.replace(c,'').replace(' ',' ')

return s

Ive tried this code above ^

but the output is:

Th some sentence know it a long one

instead of: This some sentence know it a long one

1

u/throwaway8u3sH0 Apr 28 '22

Pretty good. You're close. The problem is that you're replacing the stop words in the entire sentence, instead of comparing individual words. So you're removing "is" (the word), but also removing the letters "is" from "This", which is not what you want.

I'm surprised someone suggested looping over the stop words. The technical term for what you're doing is filtering. You're filtering words out of a sentence when they satisfy a condition. (When you get to more advanced Python, you can do things like this in a single line: " ".join(filter(lambda x: x not in stop_words.split(), sentence.split()))). But it's important to learn it with loops first.

Personally, I would do the following:

  • split both the sentence and the stop words into lists of words.

  • Loop over the words in the sentence, checking if each word is in the stop list. You can test if a word is in a list in python with something like if word in myList.

    • If it's not, I'd add it to an output list.

    • If it is, I'd skip it (do nothing).

  • Lastly, you'll need to join() the output list back together with spaces to make a sentence again.

Good luck!