问题
So, I have a list of words like so:
activationWords = ['cactus', 'cacti', 'rofl']
And I want to find any of those words and return the first word of any of those words appearing in a random string. I'll use this string as an example:
str = "Wow, rofl I found a cactus in a cacti pile."
As you can see with the above example string, the first instance of a word in the list is "rofl". I want to be able to detect that and return the word into a string that I can use to my discretion. How would I do this?
Keep in mind that that string is just an example. Each time I run this it will be using a different string.
回答1:
You can use str.find() here:
>>> activationWords = ['cactus', 'cacti', 'rofl']
>>> s = "Wow, rofl I found a cactus in a cacti pile."
>>> temp = [(s.find(i), i) for i in activationWords if i in s]
>>> print temp
[(20, 'cactus'), (32, 'cacti'), (5, 'rofl')]
>>> print min(temp)[1]
rofl
str.find()
finds where the string is in the other string. It returns the index of the first letter.
[(s.find(i), i) for i in activationWords]
is a list comprehension that returns a list of tuples, the first item being the result of str.find()
, the second being the word.
Then we use min() here to get the lowest number, and [1]
to get the word.
Note that you should not name a string str
. It overrides the built-in type.
来源:https://stackoverflow.com/questions/18807905/grab-the-first-word-in-a-list-that-is-found-in-a-string-python