Home > Software design >  Find the word detected by the any() function
Find the word detected by the any() function

Time:10-30

My question is pretty simple, but I haven't been able to find a proper solution. Given below is my program:

given_list   = ["Terms","I","want","to","remove","from","input_string"]
input_string = input("Enter String:")
if any(x in input_string for x in given_list):
     #Find the detected word
     #Not in bool format
     a = input_string.replace(detected_word,"")
     print("Some Task",a)

Here, given_list contains the terms I want to exclude from the input_string. Now, the problem I am facing is that the any() produces a bool result and I need the word detected by the any() and replace it with a blank, so as to perform some task.

CodePudding user response:

Iterate over given_list and replace them:

for i in given_list:
    input_string = input_string.replace(i, "")
print("Some Task", input_string)

CodePudding user response:

No need to detect at all:

for w in given_list:
     input_string = input_string.replace(w, "")

str.replace will not do anything if the word is not there and the substring test needed for the detection has to scan the string anyway.

CodePudding user response:

The problem with finding each word and replacing it is that python will have to iterate over the whole string, repeatedly. Another problem is you will find substrings where you don't want to. For example, "to" is in the exclude list, so you'd end up changing "tomato" to "ma"

It seems to me like you seem to want to replace whole words. Parsing is a whole new subject, but let's simplify. I'm just going to assume everything is lowercase with no punctuation, although that can be improved later. Let's use input_string.split() to iterate over whole words.

We want to replace some words with nothing, so let's just iterate over the input_string, and filter out the words we don't want, using the builtin function of the same name.

exclude_list   = ["terms","i","want","to","remove","from","input_string"]
input_string = "one terms two i three want to remove"
keepers = filter(lambda w: w not in exclude_list, input_string.lower().split())
output_string = ' '.join(keepers)
print (output_string)

one two three

Note that we create an iterator that allows us to go through the whole input string just once. And instead of replacing words, we just basically skip the ones we don't want by having the iterator not return them.

Since filter requires a function for the boolean check on whether to include or exclude each word, we had to define one. I used "lambda" syntax to do that. You could just replace it with

def keep(word):
    return word not in exclude_list

keepers = filter(keep, input_string.split())

CodePudding user response:

To answer your question about any, use an assignment expression (Python 3.8 ).

if any((word := x) in input_string for x in given_list):
    # match captured in variable word
  • Related