【问题标题】:Python: Finding a substring within a string from a list, but saving the substringPython:从列表中查找字符串中的子字符串,但保存子字符串
【发布时间】:2016-10-21 03:14:22
【问题描述】:

基本上,我有一个要搜索字符串的子字符串列表。如果在字符串中找到其中一个单词,我目前正在使用 any() 并做一些工作。我想开始记录比赛以保留比赛的一些统计数据。我现在正在使用任何()。

有没有办法做同样的事情,但将匹配存储在一个变量中?我每 10 秒获取和搜索多达 100 个字符串,以获取 25-30 个子字符串的列表。我能想到的唯一一件事是遍历列表中每个字符串的每个子字符串,但我不确定这种方法对性能的影响。

【问题讨论】:

    标签: python string list substring any


    【解决方案1】:

    我们来看这个例子:

    s = "Thisisarandomstringthatiwanttotype"
    subst = ["This", "random", "hullo", "type"]
    

    返回所有匹配的子字符串:

    filter(lambda x: x in s, subs)
    >> ['This', 'random', 'type']
    

    要返回匹配的子字符串的起始索引,您可以将从上面的代码段返回的字符串列表传递给映射函数以查找它们的索引:

    map(lambda x: s.index(x), filter(lambda x: x in s, subs))
    >> [0, 7, 30]
    

    同样,您可以在过滤器上使用 map 来检查返回字符串的长度:

    map(lambda x: len(x), filter(lambda x: x in s, subs))
    >> [4, 6, 4]
    

    或者求返回的最长子串的长度:

    max(filter(lambda x: x in s, subst), key=len)
    >> 'random'
    

    【讨论】:

      【解决方案2】:

      有多种方法可以做到这一点。正则表达式(正如 FreddieV4 建议的那样)非常强大。

      然而,另一种简单的方法是使用列表推导,例如:

      matches = [x for x in string.split() if x in substrings]
      

      这将遍历字符串中的单词并检查单词是否适合子字符串之一,如果适合,它将被返回,因此可用于记录目的。

      您甚至可以进一步扩展它以处理作为输入的字符串列表而不是单个字符串 - 所有这些都在单个列表理解中。

      一个扩展的例子如下所示:

      substrings = ["cool","test","notpresent"]
      
      #get matches for a single string
      string = "This is a basic test"
      matches = [x for x in string.split() if x in substrings]
      print(matches)
      # >> ['test']
      
      
      #get matches for multiple strings
      strings = ["I am so awesome", "you are cool", "I think so", "Yep this is a test"]
      matches = [x for string in strings for x in string.split() if x in substrings]
      print(matches)
      # >> ['cool', 'test']
      

      【讨论】:

      • 你需要拆分字符串。
      • 为什么是@JaredGoguen?
      • x for x in string 将遍历 string 中的各个字符。
      • 这真的很有趣。x for string in strings for x in string.split() if x in substrings 看起来很疯狂!我正在迭代字符串以用于其他目的,因此第一个带有单个字符串的示例可能会满足我的需要。谢谢!
      • 确实如此,但这种行为类似于 OP 当前使用的 any() 函数。如果他想要更大的灵活性,正则表达式是更好的选择。
      【解决方案3】:

      对于这类事情,您可以使用re 模块。

      >>> import re
      >>> m = re.search(r"substring1, substring2, substring3", string)
      

      string 将是您正在搜索的字符串,m 将是包含与您正在寻找的任何子字符串匹配的字符串组的变量,即substring1, substring2, substring3;您也可以使用 RegEx 模式而不是子字符串。

      【讨论】:

      • 这会将所有匹配的子字符串存储在m 中还是只存储第一个?
      猜你喜欢
      • 2023-04-03
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多