0

How can we know which word is present by using this??

word_list = ['hello','hi','super']
if any(word in string for word in word_list):
    print('found')  

By this I’m able to iterate through the lines, but unable to find which word it had found in that line.

Example: Consider 4 lines in input

Hello samuel\n
Hi how are you\n
I’m super\n
Thanks

output expected:

Hello,true
Hi,true
Super,true
N/a,false

But can someone let me know how to print the word as well which it had found in it.

user2653663
  • 2,818
  • 1
  • 18
  • 22
Core work
  • 3
  • 3

2 Answers2

0

Here's one way to do:

Word_list=['hello','hi','super']

l = ["Hello samuel","Hi how are you","I’super","Thankq"]

for i in l:
    k = [x for x in i.split(' ') if x.lower() in Word_list]
    if k:
        print(f'{k[0]}, true')
    else:
        print(f'N/A, false')

Hello, true
Hi, true
N/A, false
N/A, false
YOLO
  • 20,181
  • 5
  • 20
  • 40
0

You can do something like this:

str = """Hello samuel
Hi how are you
hi I’super
Thankq"""


word_list=["hello","hi","super"]

for line in str.split("\n"):
    word_found = [word.lower() in line.lower() for word in word_list]
    word_filtered = [i for (i, v) in zip(word_list, word_found) if v]
    print("{},{}".format(" ".join(word_filtered) if word_filtered else "n/a", not not word_filtered))

Basically what word in string for word in word_list of yours does is creating a list [True, False, False] depending which line you are currently processing. anyonly checks if any of the element in the list is True and returns true.

With this knowledge we can construct something like this.

word_found = [word.lower() in line.lower() for word in word_list] this generates the boolean list with Trueif the line contains the word on this position and False otherwise. As you see I user lower() to be case insensitive. If this is not what you want please change. But from your output it looks like this is what you want.

word_filtered = [i for (i, v) in zip(word_list, word_found) if v] with this I filter out all the words that doesn't exist in the line.

print("{},{}".format(" ".join(word_filtered) if word_filtered else "n/a", not not word_filtered)) this is to create your expected output.

Output:

hello,True
hi,True
hi super,True
n/a,False

As you see I modified your input a bit (see line 3). As you can see this solution prints any word even if there is multiple matches on a line.

Boendal
  • 2,496
  • 1
  • 23
  • 36