抓取在字符串中找到的列表中的第一个单词. ( Python ) [英] Grab the first word in a list that is found in a string. ( Python )
问题描述
所以,我有一个像这样的单词列表:
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."
如上面的示例字符串所示,列表中单词的第一个实例是"rofl".我希望能够检测到该问题并将该单词返回一个字符串,我可以根据自己的判断使用该字符串.我该怎么办?
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.
推荐答案
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()
查找该字符串在另一个字符串中的位置.它返回第一个字母的索引.
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]
是一个列表推导,返回一个元组列表,第一项是str.find()
的结果,第二项是单词.
[(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.
然后我们在此处使用 min()
来获得最低的数字,然后按[1]
即可获得单词.
Then we use min()
here to get the lowest number, and [1]
to get the word.
请注意,您不应将字符串命名为str
.它会覆盖内置类型.
Note that you should not name a string str
. It overrides the built-in type.
这篇关于抓取在字符串中找到的列表中的第一个单词. ( Python )的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!