r/pythonhelp • u/itachiwasright • 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
1
u/bulaybil Apr 27 '22
First question: do you have a list of stop words?
1
u/itachiwasright Apr 27 '22
Yes, the stop_words are "and is I" giving in the simple sentence =,
the stop words can also be of any length given as it is a string
2
u/CraigAT Apr 27 '22
You might want to look up the "split" function to give you a list of the individual words in the stop_words, you could then loop through those words and search if the current stop_word was in the sentence and remove it. Note you will have to check whether it was a full or part word within the sentence.
1
u/skellious Apr 27 '22
if doing this, DO NOT try to modify the words during looping through them, instead create a new output.
if you modify while looping you may run in to issues.
1
u/CraigAT Apr 27 '22 edited Apr 27 '22
Wouldn't you only run into issues if you were modifying the list you were looping through.
But in this instance you would be looping through the list (of stop_words) and amending a separate string (the sentence).
1
u/skellious Apr 27 '22
depending on how the fucntion is written it might do that. I'm saying to avoid writing it that way.
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