Reputation: 227
I have a list with words I wish to look for in another list:
listex = ['cat', 'mouse', 'dog']
And another list which is the one I wish to search through with the respective words in the list above:
listsearch = ['Hi there is a rabbit', 'how many dogs?', 'hot weather']
My thought is to use regex for each of the words in 'listex' on each of the strings in 'listsearch'. My goal is to get the index of the string in 'listsearch' that has been matched. For now, I have tried the following:
for search in listsearch:
x = search
if re.search(r"(?=("+'|'.join(listex)+r"))",x) is not None:
a = re.search(r"(?=("+'|'.join(listex)+r"))",x)
a=a.group(1)
print(a)
dog
So what my current code gives me is the output "dog". But what I wish to get is the index that was matched in the "listsearch" - i.e. in the example above, I wish to get the index 1, as that is the index in "listsearch" that contains the word "dog"
Any ideas on how to get the index in the case?
Upvotes: 0
Views: 6583
Reputation: 47
For a basic question, should "list comprehension" really be involved in the answer? I mean, I was thinking that someone might have wanted to have told him that regex wasn't necessary at all here, but if we want to use it maybe something a bit more basic could suffice.
import re
listex = ['cat', 'mouse', 'dog']
listsearch = ['Hi there is a rabbit', 'how many dogs?', 'hot weather']
for i in range(len(listex)):
for ii in range(len(listsearch)):
if re.findall(listex[i], listsearch[ii]):
print(str(ii)+': '+listex[i])
Output:
1: dog
Explanation:
Upvotes: 0
Reputation: 57033
You can make your code much simpler:
results = [re.search('|'.join(listex),l) for l in listsearch]
#[None, <_sre.SRE_Match object; span=(9, 12), match='dog'>, None]
indexes = [i for i,v in enumerate(results) if v]
#[1]
Upvotes: 1