Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find indexes of items in list of string in an string with Python

I'm looking for a fast approach to find all the indexes in string which match with items (one or multiple words). Actually I do not need index in list I need index in string.

I have a list of words and an string like these:

words = ['must', 'shall', 'may','should','forbidden','car',...]
string= 'you should wash the car every day'

desired output:
[1,4]# should=1, car=4

The length of list some times can be more than hundreds of items and string more that tens of thousands.

I'm looking for a so fast approach because it is called a thousand times in each iteration.

I know how to implement it with loops and check all the items one-by-one but it's so slow!

like image 789
Sina Avatar asked Nov 22 '25 05:11

Sina


1 Answers

One solution is make words set instead of list and then do simple list comprehension:

words = {'must', 'shall', 'may','should','forbidden','car'}
string= 'you should wash the car every day'

out = [i for i, w in enumerate(string.split()) if w in words]

print(out)

Prints:

[1, 4]
like image 167
Andrej Kesely Avatar answered Nov 23 '25 19:11

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!