【问题标题】:Python: Extract sublist between strings containing keywordsPython:在包含关键字的字符串之间提取子列表
【发布时间】:2021-05-31 09:17:31
【问题描述】:

我有一个字符串列表,现在我想提取包含特定关键字(包括这两个字符串)的两个字符串之间的所有字符串。

example_list = ['test sentence', 'the sky is blue', 'it is raining outside', 'mic check', 'vacation time']
keywords = ['sky', 'check']

我想要达到的结果:

result = ['the sky is blue', 'it is raining outside', 'mic check']

到目前为止,我自己无法弄清楚。 也许可以使用两个循环并使用正则表达式?

【问题讨论】:

    标签: python string list substring sublist


    【解决方案1】:

    您可以使用关键字找到字符串的索引,然后使用第一次和最后一次出现的索引对值列表进行切片

    indices = [i for i, x in enumerate(example_list) if any(k in x for k in keywords)]
    result = example_list[indices[0]:indices[-1] + 1]
    # ['the sky is blue', 'it is raining outside', 'mic check']
    

    【讨论】:

      【解决方案2】:

      这是一个更冗长的解决方案,但这是另一种方法

      found = False
      s=0
      c=0
      for i in range(len(example_list)):
          if not found and keywords[0] in example_list[i]:
              found = True
              s = i
          elif found and keywords[1] in example_list[i]:
              c = i+1
      out = example_list[s:c]
      

      【讨论】:

        【解决方案3】:

        适用于任何字符串序列的生成器解决方案,而不仅仅是列表:

        def included(seq, start_text, end_text):
            do_yield = False
            for text in seq:
                if not do_yield and start_text in text:
                    do_yield = True
                if do_yield:
                    yield text
                    if end_text in text:
                        break
        

        当然,您可以将结果转换为列表。

        【讨论】:

          【解决方案4】:

          对于每个单词,您必须检查每个句子中的存在。所以你会有 2 个循环。

          最简单的方法是使用示例列表中句子的位置(索引):

          import numpy as np
          
          example_list = ['test sentence', 'the sky is blue', 'it is raining outside', 'mic check', 'vacation time']
          keywords = ['sky', 'check']
          
          indexes=[]
          for k in keywords : 
              for sentence in example_list :
                  if k in sentence :
                      indexes.append(example_list.index(sentence))
          
          result = example_list[np.min(indexes):np.max(indexes)+1]
          print(result)
          

          它会返回:

          ['the sky is blue', 'it is raining outside', 'mic check']
          

          【讨论】:

          • 我想你错过了'it is raining outside',如果我没记错的话也应该包括在内
          • 你是对的@Vall0n!我误读了这个问题。我进行了编辑以正确回答。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-12-02
          • 2016-04-15
          • 1970-01-01
          • 1970-01-01
          • 2021-09-08
          • 2022-10-24
          • 1970-01-01
          相关资源
          最近更新 更多