【问题标题】:Grab the first word in a list that is found in a string. ( Python )抓取在字符串中找到的列表中的第一个单词。 ( Python )
【发布时间】:2013-09-15 00:55:50
【问题描述】:

所以,我有一个这样的单词列表:

activationWords = ['cactus', 'cacti', 'rofl']

我想找到这些单词中的任何一个,并返回随机字符串中出现的任何这些单词的第一个单词。我将以这个字符串为例:

str = "Wow, rofl I found a cactus in a cacti pile."

从上面的示例字符串中可以看出,列表中单词的第一个实例是“rofl”。我希望能够检测到这一点并将这个词返回到一个我可以自行决定使用的字符串中。我该怎么做?

请记住,该字符串只是一个示例。每次我运行它都会使用不同的字符串。

【问题讨论】:

    标签: python string list get word


    【解决方案1】:

    您可以在这里使用str.find():

    >>> 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() 查找字符串在另一个字符串中的位置。它返回第一个字母的索引。

    [(s.find(i), i) for i in activationWords] 是一个列表推导式,它返回一个元组列表,第一项是str.find() 的结果,第二项是单词。

    那我们这里用min()得到最小的数字,用[1]得到单词。

    请注意,您不应将字符串命名为 str。它覆盖了内置类型。

    【讨论】:

    • 哇,这真的很有帮助。非常感谢。 :)
    • @WinneonSword 不客气!别忘了accept the answer :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多