如何解决Python:在包含关键字的字符串之间提取子列表
我有一个字符串列表,现在我想提取包含特定关键字(包括这两个字符串)的两个字符串之间的所有字符串。
example_list = ['test sentence','the sky is blue','it is raining outside','mic check','vacation time']
keywords = ['sky','check']
我想要达到的结果:
result = ['the sky is blue','mic check']
到目前为止,我自己无法弄清楚。 也许可以使用两个循环并使用正则表达式?
解决方法
您可以找到带有关键字的字符串的索引,然后使用第一次和最后一次出现的索引对值列表进行切片
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 个循环。
最简单的方法是使用示例列表中句子的位置(索引):
import numpy as np
example_list = ['test sentence','the sky is blue','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','mic check']
,
这是一个更冗长的解决方案,但这是另一种方法
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]
,
一个可以处理任何字符串序列的生成器解决方案,而不仅仅是一个列表:
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
当然,您可以将结果转换为列表。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。