0

I have a list of strings generated from a text file and I need to test an input string to see if it has any of the words in my list. I then need to store the matching string/strings so that they can be used later. Currently I am using

has_words = any(string in op_text for string in words)

but I believe this only returns true/false.

2 Answers 2

6

You can create a list of matching words instead, using a list comprehension:

matching = [string for string in words if string in op_text]
Sign up to request clarification or add additional context in comments.

1 Comment

ok, a followup question. I have my words being imported from a text file where each line is a separate string that I am interested in searching for. words = open(fileName, 'database.doc') Will this matching have each index be a line in the document even if the line has spaces (ie multiple words in the line)?
0

Depending on what so that they can be used later means, you can use a set...

op_words = {'one', 'bob', 'whatever'}
matching = op_words.intersection(words)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.